import api from './client'

export interface InvoiceLine {
  id: string
  invoice_id: string
  order_line_id: string | null
  description: string
  quantity: number
  unit_price: number | null
  total: number | null
}

export interface Invoice {
  id: string
  tenant_id: string | null
  invoice_number: string
  status: 'draft' | 'sent' | 'paid' | 'cancelled'
  issued_at: string | null
  due_at: string | null
  total_net: number | null
  total_vat: number | null
  vat_rate: number
  currency: string
  notes: string | null
  pdf_key: string | null
  created_at: string
  lines: InvoiceLine[]
}

export interface InvoiceCreate {
  order_line_ids: string[]
  notes?: string
  issued_at?: string
  due_at?: string
  vat_rate?: number
  currency?: string
}

export async function getInvoices(skip = 0, limit = 50): Promise<Invoice[]> {
  const res = await api.get<Invoice[]>('/billing/invoices', { params: { skip, limit } })
  return res.data
}

export async function getInvoice(id: string): Promise<Invoice> {
  const res = await api.get<Invoice>(`/billing/invoices/${id}`)
  return res.data
}

export async function createInvoice(data: InvoiceCreate): Promise<Invoice> {
  const res = await api.post<Invoice>('/billing/invoices', data)
  return res.data
}

export async function updateInvoiceStatus(id: string, status: string): Promise<Invoice> {
  const res = await api.patch<Invoice>(`/billing/invoices/${id}`, { status })
  return res.data
}

export async function deleteInvoice(id: string): Promise<void> {
  await api.delete(`/billing/invoices/${id}`)
}

export async function downloadInvoicePdf(id: string): Promise<void> {
  const res = await api.get(`/billing/invoices/${id}/pdf`, { responseType: 'blob' })
  const url = URL.createObjectURL(res.data)
  const a = document.createElement('a')
  a.href = url
  a.download = `invoice-${id}.pdf`
  a.click()
  URL.revokeObjectURL(url)
}
