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 (let i = 0; i < propertyStore.length; i++) {
      const prop = propertyStore[i]
      const idx = (prop.units ?? []).findIndex(u => u.id === unitId)
      if (idx === -1) continue
      // Immutable update: neue Referenzen (Unit, units-Array, Property), damit React Query
      // die Änderung via Structural-Sharing erkennt und neu rendert.
      const nextUnits = [...prop.units!]
      nextUnits[idx] = { ...nextUnits[idx], ...data }
      propertyStore[i] = { ...prop, units: nextUnits }
      return nextUnits[idx]
    }
    throw new Error(`Unit ${unitId} not found`)
  },
}
