import type { IFutureSignalProvider, FutureSignalFilters } from './IFutureSignalProvider'
import type { FutureSignal } from '../domain/futureSignal'
import type { ReviewStatus } from '../domain/enums'
import { mockFutureSignals } from '../mock-data/futureSignals'

// Mutation overrides — applied on top of the live mockFutureSignals import.
// Reading directly from mockFutureSignals (not a copied store) ensures that
// Vite HMR changes to the mock data are always reflected immediately.
const mutationOverrides = new Map<string, Partial<FutureSignal>>()

function resolve(): FutureSignal[] {
  return mockFutureSignals.map(s => {
    const override = mutationOverrides.get(s.id)
    return override ? { ...s, ...override } : s
  })
}

export const MockupFutureSignalProvider: IFutureSignalProvider = {
  async getAll(filters?: FutureSignalFilters) {
    let results = resolve()
    if (filters?.signalType) results = results.filter(s => s.signalType === filters.signalType)
    if (filters?.minProbability !== undefined) results = results.filter(s => s.probability >= filters.minProbability!)
    if (filters?.organizationId) results = results.filter(s => s.organizationId === filters.organizationId)
    if (filters?.isVerified !== undefined) results = results.filter(s => s.isVerified === filters.isVerified)
    if (filters?.sensitivityLevel) results = results.filter(s => s.sensitivityLevel === filters.sensitivityLevel)
    if (filters?.reviewStatus) results = results.filter(s => (s.reviewStatus ?? 'UNREVIEWED') === filters.reviewStatus)
    if (filters?.maxTimeHorizonMonths !== undefined) results = results.filter(s => s.timeHorizonMonths <= filters.maxTimeHorizonMonths!)
    return results.sort((a, b) => b.probability - a.probability)
  },
  async getById(id) {
    return resolve().find(s => s.id === id) ?? null
  },
  async getByProperty(propertyId) {
    return resolve().filter(s => s.propertyId === propertyId)
  },
  async verify(id, verifiedBy) {
    const existing = mutationOverrides.get(id) ?? {}
    mutationOverrides.set(id, { ...existing, isVerified: true, verifiedBy, verifiedAt: new Date().toISOString(), updatedAt: new Date().toISOString() })
    return resolve().find(s => s.id === id)!
  },
  async updateReviewStatus(id, status: ReviewStatus) {
    const existing = mutationOverrides.get(id) ?? {}
    mutationOverrides.set(id, { ...existing, reviewStatus: status, updatedAt: new Date().toISOString() })
    return resolve().find(s => s.id === id)!
  },
}
