import type { IMatchProvider, MatchFilters } from './IMatchProvider'
import type { Match } from '../domain/match'

// Populated at startup by MockupNeedProvider via syncMatchesForNeed (deterministic IDs, no duplicates)
export const matchStore: Match[] = []
const store = matchStore

export const MockupMatchProvider: IMatchProvider = {
  async getAll(filters?: MatchFilters) {
    let results = [...store]
    if (filters?.needId) results = results.filter(m => m.needId === filters.needId)
    if (filters?.propertyId) results = results.filter(m => m.propertyId === filters.propertyId)
    if (filters?.minScore) results = results.filter(m => m.matchScore >= filters.minScore!)
    if (filters?.matchStrength) results = results.filter(m => m.matchStrength === filters.matchStrength)
    if (filters?.organizationId) results = results.filter(m => m.organizationId === filters.organizationId)
    // Deduplicate by id — guards against double-push during dev hot-reload
    const seen = new Set<string>()
    results = results.filter(m => { if (seen.has(m.id)) return false; seen.add(m.id); return true })
    return results.sort((a, b) => b.matchScore - a.matchScore)
  },
  async getById(id) {
    return store.find(m => m.id === id) ?? null
  },
  async getByNeed(needId) {
    return store.filter(m => m.needId === needId).sort((a, b) => b.matchScore - a.matchScore)
  },
  async getByProperty(propertyId) {
    return store.filter(m => m.propertyId === propertyId).sort((a, b) => b.matchScore - a.matchScore)
  },
  async approve(id, reviewedBy) {
    const idx = store.findIndex(m => m.id === id)
    store[idx] = { ...store[idx], isApproved: true, reviewedBy, reviewedAt: new Date().toISOString(), updatedAt: new Date().toISOString() }
    return store[idx]
  },
}
