import { adminApi } from './client'
import { unwrapItem } from './helpers'
import { normalizeLead, normalizePaginated } from './normalizers'
import type {
  AdminLeadRecord,
  ApiItemResponse,
  ApiListResponse,
  PaginatedResult,
} from './types'

export type LeadsQuery = {
  page?: number
  perPage?: number
  search?: string
  status?: string
  source?: string
  is_read?: boolean
}

export type LeadUpdatePayload = {
  status?: string
  admin_note?: string | null
  is_read?: boolean
}

export async function fetchLeads(
  query: LeadsQuery
): Promise<PaginatedResult<AdminLeadRecord>> {
  const response = await adminApi.get<ApiListResponse<Record<string, unknown>>>(
    '/leads',
    {
      params: {
        page: query.page,
        per_page: query.perPage,
        search: query.search || undefined,
        status: query.status || undefined,
        source: query.source || undefined,
        is_read: query.is_read,
      },
    }
  )

  return normalizePaginated(response.data, normalizeLead)
}

export async function fetchLead(leadId: number | string) {
  const response = await adminApi.get<ApiItemResponse<Record<string, unknown>>>(
    `/leads/${leadId}`
  )
  return normalizeLead(unwrapItem(response))
}

export async function updateLead(
  leadId: number | string,
  payload: LeadUpdatePayload
) {
  const response = await adminApi.put<ApiItemResponse<Record<string, unknown>>>(
    `/leads/${leadId}`,
    payload
  )
  return normalizeLead(unwrapItem(response))
}

export async function deleteLead(leadId: number | string) {
  await adminApi.delete(`/leads/${leadId}`)
}
