import { api } from '../api'

export interface InvoiceItem {
  description?: string
  quantity: number
  unitPrice: number
  total?: number
}

export interface Invoice {
  id: string
  invoiceNumber: string
  dealId?: string
  deal?: any
  items: InvoiceItem[] | any
  subtotal: number
  taxAmount: number
  total: number
  status: string
  dueDate: string
  paidDate?: string
  paidAmount?: number
  createdAt: string
  updatedAt: string
}

export interface CreateInvoiceData {
  dealId?: string
  items: InvoiceItem[] | any[]
  subtotal: number
  taxAmount: number
  total: number
  dueDate: string
}

export const invoicesAPI = {
  getByDeal: async (dealId: string): Promise<Invoice[]> => {
    const response = await api.get(`/crm/deals/${dealId}/invoices`)
    return response.data.data || []
  },

  getById: async (id: string): Promise<Invoice> => {
    const response = await api.get(`/crm/invoices/${id}`)
    return response.data.data
  },

  create: async (data: CreateInvoiceData): Promise<Invoice> => {
    const response = await api.post('/crm/invoices', data)
    return response.data.data
  },

  update: async (id: string, data: Partial<CreateInvoiceData>): Promise<Invoice> => {
    const response = await api.put(`/crm/invoices/${id}`, data)
    return response.data.data
  },

  recordPayment: async (id: string, paidAmount: number, paidDate?: string): Promise<Invoice> => {
    const response = await api.post(`/crm/invoices/${id}/record-payment`, {
      paidAmount,
      paidDate: paidDate || new Date().toISOString(),
    })
    return response.data.data
  }
}
