import type { InquiryPreparationReportDraft, ReportObjectFieldSelection, ReportEditableField } from '../domain/inquiryReport'
import { mockInquiryReportDrafts } from '../mock-data/inquiryReportDrafts'

const store: InquiryPreparationReportDraft[] = mockInquiryReportDrafts.map(d => ({ ...d }))

const DEFAULT_EDITABLE_FIELDS: ReportEditableField[] = [
  { id: 'intro', label: 'Einleitung', value: 'Sehr geehrte Damen und Herren\n\nGerne präsentieren wir Ihnen passende Objekte aus unserem Portfolio.', fieldType: 'textarea' },
  { id: 'highlights', label: 'Besonderheiten', value: 'Die ausgewählten Objekte entsprechen Ihrem Anforderungsprofil.', fieldType: 'textarea' },
  { id: 'next_steps', label: 'Nächste Schritte', value: 'Für einen Besichtigungstermin stehen wir gerne zur Verfügung.', fieldType: 'textarea' },
]

const DEFAULT_FIELD_SELECTION: Omit<ReportObjectFieldSelection, 'propertyId'> = {
  mandatoryFields: ['title', 'location', 'mapImageUrl', 'images'],
  selectedOptionalFields: ['areaSqm', 'rentPricePerSqm', 'availabilityDate', 'leaseTerm', 'description'],
}

export const inquiryReportService = {
  async getByInquiry(inquiryId: string): Promise<InquiryPreparationReportDraft | null> {
    return store.find(d => d.inquiryId === inquiryId) ?? null
  },

  async create(inquiryId: string, selectedPropertyIds: string[]): Promise<InquiryPreparationReportDraft> {
    const existing = store.find(d => d.inquiryId === inquiryId)
    if (existing) return existing
    const draft: InquiryPreparationReportDraft = {
      id: crypto.randomUUID(),
      inquiryId,
      selectedPropertyIds,
      fieldSelections: selectedPropertyIds.map(propertyId => ({
        propertyId,
        ...DEFAULT_FIELD_SELECTION,
      })),
      marketSignalPropertyId: selectedPropertyIds[0],
      editableFields: DEFAULT_EDITABLE_FIELDS.map(f => ({ ...f })),
      status: 'draft',
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
    }
    store.push(draft)
    return draft
  },

  async update(draftId: string, data: Partial<InquiryPreparationReportDraft>): Promise<InquiryPreparationReportDraft> {
    const idx = store.findIndex(d => d.id === draftId)
    if (idx === -1) throw new Error(`Draft ${draftId} not found`)
    store[idx] = { ...store[idx], ...data, updatedAt: new Date().toISOString() }
    return store[idx]
  },

  async finalize(draftId: string): Promise<InquiryPreparationReportDraft> {
    const idx = store.findIndex(d => d.id === draftId)
    if (idx === -1) throw new Error(`Draft ${draftId} not found`)
    store[idx] = {
      ...store[idx],
      status: 'finalized',
      pdfUrl: `/mock-reports/${draftId}.pdf`,
      updatedAt: new Date().toISOString(),
    }
    return store[idx]
  },
}
