import type { IOfferProvider, CreateOfferDraftInput } from './IOfferProvider'
import type { OfferDraft, OfferStatus } from '../domain/offer'

const store: OfferDraft[] = []

export const MockupOfferProvider: IOfferProvider = {
  async create(input: CreateOfferDraftInput): Promise<OfferDraft> {
    const now = new Date().toISOString()
    const draft: OfferDraft = {
      id: crypto.randomUUID(),
      needId: input.needId,
      selectedPropertyIds: input.selectedPropertyIds,
      subject: input.subject,
      message: input.message,
      status: 'draft',
      editableFields: input.editableFields,
      createdAt: now,
      updatedAt: now,
    }
    store.push(draft)
    return draft
  },
  async getById(id: string): Promise<OfferDraft | null> {
    return store.find(d => d.id === id) ?? null
  },
  async updateField(id: string, fieldId: string, value: string): Promise<OfferDraft> {
    const idx = store.findIndex(d => d.id === id)
    if (idx === -1) throw new Error(`OfferDraft ${id} not found`)
    const fields = store[idx].editableFields.map(f => (f.id === fieldId ? { ...f, value } : f))
    store[idx] = { ...store[idx], editableFields: fields, updatedAt: new Date().toISOString() }
    return store[idx]
  },
  async updateStatus(id: string, status: OfferStatus): Promise<OfferDraft> {
    const idx = store.findIndex(d => d.id === id)
    if (idx === -1) throw new Error(`OfferDraft ${id} not found`)
    store[idx] = { ...store[idx], status, updatedAt: new Date().toISOString() }
    return store[idx]
  },
  async setPdfUrl(id: string, pdfUrl: string): Promise<OfferDraft> {
    const idx = store.findIndex(d => d.id === id)
    if (idx === -1) throw new Error(`OfferDraft ${id} not found`)
    store[idx] = { ...store[idx], pdfUrl, updatedAt: new Date().toISOString() }
    return store[idx]
  },
}
