import type { IShortlistProvider, ShortlistFilters } from './IShortlistProvider'
import type { Shortlist, CreateShortlistInput, UpdateShortlistInput, ShortlistItemInput } from '../domain/shortlist'
import { mockShortlists } from '../mock-data/shortlists'
import { mockDelay } from '../lib/mockUtils'

const store: Shortlist[] = [...mockShortlists]

export const MockupShortlistProvider: IShortlistProvider = {
  async getAll(filters?: ShortlistFilters) {
    await mockDelay()
    let results = [...store]
    if (filters?.needId) results = results.filter(s => s.needId === filters.needId)
    if (filters?.status) results = results.filter(s => s.status === filters.status)
    if (filters?.createdBy) results = results.filter(s => s.createdBy === filters.createdBy)
    if (filters?.organizationId) results = results.filter(s => s.organizationId === filters.organizationId)
    return results
  },
  async getById(id) {
    await mockDelay()
    return store.find(s => s.id === id) ?? null
  },
  async create(data: CreateShortlistInput) {
    await mockDelay()
    const next: Shortlist = {
      id: crypto.randomUUID(),
      ...data,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
    }
    store.push(next)
    return next
  },
  async update(id, data: UpdateShortlistInput) {
    await mockDelay()
    const idx = store.findIndex(s => s.id === id)
    store[idx] = { ...store[idx], ...data, updatedAt: new Date().toISOString() }
    return store[idx]
  },
  async addItem(id, item: ShortlistItemInput) {
    await mockDelay()
    const idx = store.findIndex(s => s.id === id)
    const alreadyAdded = store[idx].items.some(i => i.resultId === item.resultId)
    if (!alreadyAdded) {
      store[idx] = {
        ...store[idx],
        items: [...store[idx].items, { ...item, addedAt: new Date().toISOString() }],
        updatedAt: new Date().toISOString(),
      }
    }
    return store[idx]
  },
  async removeItem(id, resultId) {
    await mockDelay()
    const idx = store.findIndex(s => s.id === id)
    store[idx] = {
      ...store[idx],
      items: store[idx].items.filter(i => i.resultId !== resultId),
      updatedAt: new Date().toISOString(),
    }
    return store[idx]
  },
  async remove(id) {
    await mockDelay()
    const idx = store.findIndex(s => s.id === id)
    store.splice(idx, 1)
  },
}
