import { MockupInquiryProvider } from '../provider/MockupInquiryProvider'
import type { InquiryFilters } from '../provider/IInquiryProvider'
import type { Inquiry, Attachment } from '../domain/inquiry'

const provider = MockupInquiryProvider

export interface InquiryReplyPayload {
  subject?: string
  body: string
  attachments?: Attachment[]
}

type ServiceResult<T> = { data: T; error: null } | { data: null; error: string }

export const inquiryService = {
  async getActiveInquiries(filters?: InquiryFilters): Promise<ServiceResult<Inquiry[]>> {
    try {
      const data = await provider.getAll(filters)
      return { data, error: null }
    } catch (e) {
      return { data: null, error: e instanceof Error ? e.message : 'Unbekannter Fehler' }
    }
  },

  async getInquiryById(id: string): Promise<ServiceResult<Inquiry | null>> {
    try {
      const data = await provider.getById(id)
      return { data, error: null }
    } catch (e) {
      return { data: null, error: e instanceof Error ? e.message : 'Unbekannter Fehler' }
    }
  },

  async sendInquiryReply(
    inquiryId: string,
    payload: InquiryReplyPayload,
  ): Promise<ServiceResult<Inquiry>> {
    try {
      const data = await provider.addMessage(inquiryId, {
        senderType: 'supply_user',
        senderName: 'Wincasa AG',
        subject: payload.subject,
        body: payload.body,
        attachments: payload.attachments ?? [],
      })
      return { data, error: null }
    } catch (e) {
      return { data: null, error: e instanceof Error ? e.message : 'Unbekannter Fehler' }
    }
  },

  async markThreadAsRead(id: string): Promise<ServiceResult<Inquiry>> {
    try {
      const data = await provider.markThreadAsRead(id)
      return { data, error: null }
    } catch (e) {
      return { data: null, error: e instanceof Error ? e.message : 'Unbekannter Fehler' }
    }
  },

  async getUnreadCount(): Promise<ServiceResult<number>> {
    try {
      const data = await provider.getUnreadCount()
      return { data, error: null }
    } catch (e) {
      return { data: null, error: e instanceof Error ? e.message : 'Unbekannter Fehler' }
    }
  },
}
