import type { IInquiryProvider, InquiryFilters } from './IInquiryProvider'
import type { Inquiry, InquiryStatus, InquiryMessage } from '../domain/inquiry'
import { mockInquiries } from '../mock-data/inquiries'

const store: Inquiry[] = mockInquiries.map(i => ({ ...i, thread: [...i.thread] }))

export const MockupInquiryProvider: IInquiryProvider = {
  async getAll(filters?: InquiryFilters): Promise<Inquiry[]> {
    let results = [...store]
    if (filters?.status) results = results.filter(i => i.status === filters.status)
    if (filters?.propertyId) results = results.filter(i => i.propertyId === filters.propertyId)
    if (filters?.organizationId) results = results.filter(i => i.organizationId === filters.organizationId)
    return results.sort((a, b) => (a.createdAt < b.createdAt ? 1 : -1))
  },
  async getById(id: string): Promise<Inquiry | null> {
    return store.find(i => i.id === id) ?? null
  },
  async updateStatus(id: string, status: InquiryStatus): Promise<Inquiry> {
    const idx = store.findIndex(i => i.id === id)
    if (idx === -1) throw new Error(`Inquiry ${id} not found`)
    store[idx] = { ...store[idx], status, updatedAt: new Date().toISOString() }
    return store[idx]
  },
  async markThreadAsRead(id: string): Promise<Inquiry> {
    const idx = store.findIndex(i => i.id === id)
    if (idx === -1) throw new Error(`Inquiry ${id} not found`)
    store[idx] = {
      ...store[idx],
      isRead: true,
      unreadCount: 0,
      lastReadAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
    }
    return store[idx]
  },
  async getUnreadCount(): Promise<number> {
    return store.reduce((sum, i) => sum + (i.unreadCount ?? 0), 0)
  },
  async addMessage(
    inquiryId: string,
    msg: Omit<InquiryMessage, 'id' | 'inquiryId' | 'createdAt'>,
  ): Promise<Inquiry> {
    const idx = store.findIndex(i => i.id === inquiryId)
    if (idx === -1) throw new Error(`Inquiry ${inquiryId} not found`)
    const message: InquiryMessage = {
      id: crypto.randomUUID(),
      inquiryId,
      createdAt: new Date().toISOString(),
      ...msg,
    }
    store[idx] = {
      ...store[idx],
      thread: [...store[idx].thread, message],
      updatedAt: message.createdAt,
    }
    return store[idx]
  },
}
