import { MockupInquiryProvider } from '../provider/MockupInquiryProvider'
import type { InquiryFilters, CreateInquiryInput, CreateOfferInput } from '../provider/IInquiryProvider'
import type { Inquiry, Attachment, InquiryMessage } from '../domain/inquiry'
import type { ListResponse, ItemResponse } from './types'
import { throwServiceError } from './errors'

const provider = MockupInquiryProvider

export interface InquiryReplyPayload {
  subject?: string
  body: string
  attachments?: Attachment[]
  senderType?: InquiryMessage['senderType']   // default 'supply_user'
  senderName?: string
}

export const inquiryService = {
  async getActiveInquiries(filters?: InquiryFilters): Promise<ListResponse<Inquiry>> {
    try {
      const data = await provider.getAll(filters)
      return { data, meta: { total: data.length, page: 1, pageSize: data.length, hasMore: false } }
    } catch (err) {
      throwServiceError(err)
    }
  },

  async getInquiryById(id: string): Promise<ItemResponse<Inquiry | null>> {
    try {
      const data = await provider.getById(id)
      return { data }
    } catch (err) {
      throwServiceError(err)
    }
  },

  async createInquiry(input: CreateInquiryInput): Promise<ItemResponse<Inquiry>> {
    try {
      const data = await provider.createInquiry(input)
      return { data }
    } catch (err) {
      throwServiceError(err)
    }
  },

  async createOffer(input: CreateOfferInput): Promise<ItemResponse<Inquiry>> {
    try {
      const data = await provider.createOffer(input)
      return { data }
    } catch (err) {
      throwServiceError(err)
    }
  },

  async sendInquiryReply(
    inquiryId: string,
    payload: InquiryReplyPayload,
  ): Promise<ItemResponse<Inquiry>> {
    try {
      const data = await provider.addMessage(inquiryId, {
        senderType: payload.senderType ?? 'supply_user',
        senderName: payload.senderName ?? 'Wincasa AG',
        subject: payload.subject,
        body: payload.body,
        attachments: payload.attachments ?? [],
      })
      return { data }
    } catch (err) {
      throwServiceError(err)
    }
  },

  async markThreadAsRead(id: string): Promise<ItemResponse<Inquiry>> {
    try {
      const data = await provider.markThreadAsRead(id)
      return { data }
    } catch (err) {
      throwServiceError(err)
    }
  },

  async getUnreadCount(filters?: InquiryFilters): Promise<ItemResponse<number>> {
    try {
      const data = await provider.getUnreadCount(filters)
      return { data }
    } catch (err) {
      throwServiceError(err)
    }
  },
}
