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

// Eine gemeinsame Konversationsmenge: Supply-Eingang (mockInquiries) + Demand-Perspektive
// (mockDemandInquiries, inkl. erhaltener Angebote). Beide Seiten lesen perspektivisch gefiltert.
const store: Inquiry[] = [...mockInquiries, ...mockDemandInquiries].map(i => ({ ...i, thread: [...i.thread] }))

function applyFilters(results: Inquiry[], filters?: InquiryFilters): Inquiry[] {
  let out = results
  if (filters?.status) out = out.filter(i => i.status === filters.status)
  if (filters?.propertyId) out = out.filter(i => i.propertyId === filters.propertyId)
  if (filters?.organizationId) out = out.filter(i => i.organizationId === filters.organizationId)
  if (filters?.tenantOrgId) out = out.filter(i => i.tenantOrgId === filters.tenantOrgId)
  if (filters?.kind) out = out.filter(i => (i.kind ?? 'INQUIRY') === filters.kind)
  return out
}

export const MockupInquiryProvider: IInquiryProvider = {
  async getAll(filters?: InquiryFilters): Promise<Inquiry[]> {
    return applyFilters([...store], filters).sort((a, b) => (a.updatedAt < b.updatedAt ? 1 : -1))
  },
  async getById(id: string): Promise<Inquiry | null> {
    return store.find(i => i.id === id) ?? null
  },
  async createInquiry(input: CreateInquiryInput): Promise<Inquiry> {
    const now = new Date().toISOString()
    const id = `inq-${crypto.randomUUID().slice(0, 8)}`
    const inquiry: Inquiry = {
      id,
      kind: 'INQUIRY',
      organizationId: input.organizationId,
      tenantOrgId: input.tenantOrgId,
      propertyId: input.propertyId,
      needId: input.needId,
      tenantName: input.tenantName,
      tenantCompany: input.tenantCompany,
      tenantEmail: input.tenantEmail,
      propertyAddress: input.propertyAddress,
      subject: input.subject,
      message: input.message,
      status: 'new',
      unreadCount: 1,   // neu für die Verwaltung (Empfänger)
      isRead: false,
      matchScore: input.matchScore,
      createdAt: now,
      updatedAt: now,
      thread: [{
        id: crypto.randomUUID(),
        inquiryId: id,
        senderType: 'tenant',
        senderName: input.tenantCompany ?? input.tenantName,
        subject: input.subject,
        body: input.message,
        attachments: [],
        createdAt: now,
      }],
    }
    store.unshift(inquiry)
    return inquiry
  },
  async createOffer(input: CreateOfferInput): Promise<Inquiry> {
    const now = new Date().toISOString()
    const id = `off-${crypto.randomUUID().slice(0, 8)}`
    const inquiry: Inquiry = {
      id,
      kind: 'OFFER',
      organizationId: input.organizationId,
      tenantOrgId: input.tenantOrgId,
      propertyId: input.propertyId,
      offeredPropertyIds: input.offeredPropertyIds,
      needId: input.needId,
      tenantName: input.recipientName ?? '',
      propertyManagerCompany: input.senderName,
      subject: input.subject,
      message: input.message,
      status: 'new',
      unreadCount: 1,   // neu für den Nachfrager (Empfänger)
      isRead: false,
      createdAt: now,
      updatedAt: now,
      thread: [{
        id: crypto.randomUUID(),
        inquiryId: id,
        senderType: 'supply_user',
        senderName: input.senderName,
        subject: input.subject,
        body: input.message,
        attachments: input.attachments ?? [],
        createdAt: now,
      }],
    }
    store.unshift(inquiry)
    return inquiry
  },
  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(filters?: InquiryFilters): Promise<number> {
    return applyFilters([...store], filters).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],
      // Neue Nachricht der Gegenseite → für den Empfänger ungelesen
      unreadCount: (store[idx].unreadCount ?? 0) + 1,
      isRead: false,
      status: store[idx].status === 'new' ? 'in_progress' : store[idx].status,
      updatedAt: message.createdAt,
    }
    return store[idx]
  },
}
