import { MockupPropertyProvider } from '../provider/MockupPropertyProvider'
import type { PropertyFilters } from '../provider/IPropertyProvider'
import type { CreatePropertyInput, UpdatePropertyInput } from '../domain/property'
import type { ListResponse, ItemResponse } from './types'
import type { Property } from '../domain/property'
import { throwServiceError } from './errors'

const provider = MockupPropertyProvider
const ACTIVE_STATUSES: readonly string[] = ['AVAILABLE_NOW', 'AVAILABLE_SOON']

export const propertyService = {
  async getAll(filters?: PropertyFilters): Promise<ListResponse<Property>> {
    try {
      const data = await provider.getAll(filters)
      return { data, meta: { total: data.length, page: 1, pageSize: data.length, hasMore: false } }
    } catch (err) {
      throwServiceError(err)
    }
  },
  async getById(id: string): Promise<ItemResponse<Property | null>> {
    try {
      const data = await provider.getById(id)
      return { data }
    } catch (err) {
      throwServiceError(err)
    }
  },
  async create(input: CreatePropertyInput): Promise<ItemResponse<Property>> {
    try {
      const data = await provider.create(input)
      return { data }
    } catch (err) {
      throwServiceError(err)
    }
  },
  async update(id: string, input: UpdatePropertyInput): Promise<ItemResponse<Property>> {
    try {
      const data = await provider.update(id, input)
      return { data }
    } catch (err) {
      throwServiceError(err)
    }
  },
  async remove(id: string): Promise<ItemResponse<void>> {
    try {
      await provider.remove(id)
      return { data: undefined }
    } catch (err) {
      throwServiceError(err)
    }
  },

  async getDashboardPropertiesSummary(): Promise<{ total: number; active: number }> {
    try {
      const data = await provider.getAll()
      return {
        total: data.length,
        active: data.filter(p => ACTIVE_STATUSES.includes(p.availabilityStatus)).length,
      }
    } catch (err) {
      throwServiceError(err)
    }
  },

  async getProperties(filters?: PropertyFilters): Promise<ListResponse<Property>> {
    try {
      const data = await provider.getAll(filters)
      return { data, meta: { total: data.length, page: 1, pageSize: data.length, hasMore: false } }
    } catch (err) {
      throwServiceError(err)
    }
  },
}
