import type { INeedProvider, NeedFilters } from './INeedProvider'
import type { Need, CreateNeedInput, UpdateNeedInput } from '../domain/need'
import { mockNeeds } from '../mock-data/needs'
import { generateMatchesForNeed, syncMatchesForNeed } from '../services/matchSyncService'

const store: Need[] = [...mockNeeds]

// ── Provider ───────────────────────────────────────────────────────────────────

export const MockupNeedProvider: INeedProvider = {
  async getAll(filters?: NeedFilters) {
    let results = [...store]
    if (filters?.assetType) results = results.filter(n => n.assetType === filters.assetType)
    if (filters?.organizationId) results = results.filter(n => n.organizationId === filters.organizationId)
    if (filters?.companyName) results = results.filter(n => n.companyName.toLowerCase().includes(filters.companyName!.toLowerCase()))
    return results
  },
  async getById(id) {
    return store.find(n => n.id === id) ?? null
  },
  async create(data: CreateNeedInput) {
    const next: Need = { id: crypto.randomUUID(), ...data, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString() }
    store.push(next)
    generateMatchesForNeed(next)
    return next
  },
  async update(id, data: UpdateNeedInput) {
    const idx = store.findIndex(n => n.id === id)
    store[idx] = { ...store[idx], ...data, updatedAt: new Date().toISOString() }
    // Remove old matches and recompute with updated weights
    syncMatchesForNeed(store[idx])
    return store[idx]
  },
  async remove(id) {
    const idx = store.findIndex(n => n.id === id)
    store.splice(idx, 1)
  },
}

// Recompute matches for all pre-existing needs — replaces static mock matches so scores reflect need.weightingProfile
for (const need of store) {
  syncMatchesForNeed(need)
}
