import { api } from '@/services/api'
import type { Invoice, Paginated } from '@/modules/invoice/services/invoiceService'

export interface CustomerPortalLoginPayload {
  company_slug: string
  email: string
  password: string
  device_name?: string
}

export interface CustomerPortalAccount {
  id: number
  name: string
  email: string
  status: string
  customer: {
    id: number
    name: string
    email: string | null
    phone: string | null
  }
  company: {
    id: number
    name: string
    slug: string
  }
  last_login_at: string | null
}

export interface CustomerPortalDashboard {
  total_invoices: number
  unpaid_invoices: number
  overdue_invoices: number
  total_due: string
  latest_invoices: Invoice[]
}

export interface CustomerPortalProfilePayload {
  name: string
  email: string
  current_password?: string
  password?: string
  password_confirmation?: string
}

export interface CustomerPortalInvoiceFilters {
  search?: string
  status?: string
  date_from?: string
  date_to?: string
  due_only?: boolean
  page?: number
  per_page?: number
}

export const customerPortalService = {
  async login(payload: CustomerPortalLoginPayload) {
    const { data } = await api.post<{
      data: {
        account: CustomerPortalAccount
        token: string
        token_type: string
      }
    }>('/customer-portal/auth/login', payload)

    return data.data
  },

  async logout() {
    await api.post('/customer-portal/auth/logout')
  },

  async me() {
    const { data } = await api.get<{ data: CustomerPortalAccount }>('/customer-portal/me')

    return data.data
  },

  async updateProfile(payload: CustomerPortalProfilePayload) {
    const { data } = await api.put<{ data: CustomerPortalAccount }>('/customer-portal/profile', payload)

    return data.data
  },

  async dashboard() {
    const { data } = await api.get<{ data: CustomerPortalDashboard }>('/customer-portal/dashboard')

    return data.data
  },

  async invoices(filters: CustomerPortalInvoiceFilters = {}) {
    const { data } = await api.get<{ data: Invoice[] }>('/customer-portal/invoices', {
      params: filters,
    })

    return data.data
  },

  async paginatedInvoices(filters: CustomerPortalInvoiceFilters = {}) {
    const { data } = await api.get<{ data: Paginated<Invoice> }>('/customer-portal/invoices', {
      params: filters,
    })

    return data.data
  },

  async invoice(id: number | string) {
    const { data } = await api.get<{ data: Invoice }>(`/customer-portal/invoices/${id}`)

    return data.data
  },

  async exportInvoiceHtml(id: number | string) {
    const { data } = await api.get<Blob>(`/customer-portal/invoices/${id}/export/html`, {
      responseType: 'blob',
    })

    return data
  },
}
