// ADM-009 — API client tipado para fiscal/iva
import { axiosClient } from '@/api/axiosClient'
import type {
  TipoDeIva,
  CreateTipoDeIvaRequest,
  UpdateTipoDeIvaRequest,
  NuevaVersionTipoDeIvaRequest,
  NuevaVersionResponse,
  HistorialCadenaEntry,
  TipoDeIvaFilter,
  PagedResponse,
} from '../types/tipoDeIva.types'

const BASE = '/api/v1/admin/fiscal/iva'

export async function listTiposDeIva(
  params: TipoDeIvaFilter,
): Promise<PagedResponse<TipoDeIva>> {
  const p = new URLSearchParams()
  if (params.page !== undefined) p.set('page', String(params.page))
  if (params.pageSize !== undefined) p.set('pageSize', String(params.pageSize))
  if (params.codigo !== undefined) p.set('codigo', params.codigo)
  if (params.activo !== undefined) p.set('activo', String(params.activo))

  const res = await axiosClient.get<PagedResponse<TipoDeIva>>(BASE, { params: p })
  return res.data
}

export async function getTipoDeIvaById(id: number): Promise<TipoDeIva> {
  const res = await axiosClient.get<TipoDeIva>(`${BASE}/${id}`)
  return res.data
}

export async function getHistorialTipoDeIva(id: number): Promise<HistorialCadenaEntry[]> {
  const res = await axiosClient.get<HistorialCadenaEntry[]>(`${BASE}/${id}/historial`)
  return res.data
}

export async function createTipoDeIva(body: CreateTipoDeIvaRequest): Promise<TipoDeIva> {
  const res = await axiosClient.post<TipoDeIva>(BASE, body)
  return res.data
}

export async function updateTipoDeIva(
  id: number,
  body: UpdateTipoDeIvaRequest,
): Promise<TipoDeIva> {
  const res = await axiosClient.patch<TipoDeIva>(`${BASE}/${id}`, body)
  return res.data
}

export async function nuevaVersionTipoDeIva(
  id: number,
  body: NuevaVersionTipoDeIvaRequest,
): Promise<NuevaVersionResponse> {
  const res = await axiosClient.post<NuevaVersionResponse>(`${BASE}/${id}/nueva-version`, body)
  return res.data
}

export async function deactivateTipoDeIva(id: number): Promise<TipoDeIva> {
  const res = await axiosClient.post<TipoDeIva>(`${BASE}/${id}/deactivate`)
  return res.data
}

export async function reactivateTipoDeIva(id: number): Promise<TipoDeIva> {
  const res = await axiosClient.post<TipoDeIva>(`${BASE}/${id}/reactivate`)
  return res.data
}
