import type { IUnitProvider } from './IUnitProvider'
import type { PropertyUnit } from '../domain/property'
import { propertyStore } from '../mock-data/propertyStore'

function getAllUnits(): PropertyUnit[] {
  return propertyStore.flatMap(p =>
    (p.units ?? []).map(u => ({ ...u, propertyId: u.propertyId ?? p.id })),
  )
}

export const MockupUnitProvider: IUnitProvider = {
  async getByPropertyId(propertyId: string) {
    const prop = propertyStore.find(p => p.id === propertyId)
    return (prop?.units ?? []).map(u => ({ ...u, propertyId }))
  },
  async getById(unitId: string) {
    return getAllUnits().find(u => u.id === unitId) ?? null
  },
  async update(unitId: string, data: Partial<PropertyUnit>) {
    for (const prop of propertyStore) {
      const idx = (prop.units ?? []).findIndex(u => u.id === unitId)
      if (idx === -1) continue
      prop.units![idx] = { ...prop.units![idx], ...data }
      return prop.units![idx]
    }
    throw new Error(`Unit ${unitId} not found`)
  },
}
