import { api } from '@/services/api'

export interface PosSaleItem {
  id: number
  product_id: number
  description: string
  sku: string | null
  quantity: string
  unit_price: string
  discount_amount: string
  tax_rate: string
  tax_amount: string
  line_total: string
}

export interface PosSale {
  id: number
  financial_account?: {
    id: number
    name: string
    type: string
  } | null
  sale_number: string
  sale_date: string
  subtotal: string
  discount_total: string
  tax_total: string
  total: string
  paid_total: string
  change_total: string
  payment_method: string
  payment_status: string
  status: string
  items?: PosSaleItem[]
}

export interface PosSaleFilters {
  search?: string
  payment_method?: string
  payment_status?: string
  status?: string
  date_from?: string
  date_to?: string
  page?: number
  per_page?: number
}

export interface PaginationMeta {
  current_page: number
  from: number | null
  last_page: number
  per_page: number
  to: number | null
  total: number
}

export interface Paginated<T> {
  data: T[]
  meta: PaginationMeta
}

export const posService = {
  async sales(filters: PosSaleFilters = {}) {
    const { data } = await api.get<{ data: PosSale[] }>('/pos/sales', {
      params: filters,
    })

    return data.data
  },

  async paginatedSales(filters: PosSaleFilters = {}) {
    const { data } = await api.get<{ data: Paginated<PosSale> }>('/pos/sales', {
      params: filters,
    })

    return data.data
  },

  async createSale(payload: {
    financial_account_id?: number
    sale_date?: string
    payment_method?: string
    paid_total?: number
    items: Array<{
      product_id: number
      quantity: number
      unit_price?: number
      discount_amount?: number
      tax_rate?: number
    }>
  }) {
    const { data } = await api.post<{ data: PosSale }>('/pos/sales', payload)

    return data.data
  },

  async updateSale(sale: PosSale, payload: { status?: 'voided'; notes?: string | null }) {
    const { data } = await api.patch<{ data: PosSale }>(`/pos/sales/${sale.id}`, payload)

    return data.data
  },

  async sale(sale: PosSale) {
    const { data } = await api.get<{ data: PosSale }>(`/pos/sales/${sale.id}`)

    return data.data
  },

  async exportSaleHtml(sale: PosSale) {
    const { data } = await api.get<Blob>(`/pos/sales/${sale.id}/export/html`, {
      responseType: 'blob',
    })

    return data
  },
}
