import { api as apiClient } from "@/auth/http";
import { URL_CONSTANTS } from "@/constants/URLS";
import type {
  Invoice,
  InvoiceListFilter,
  PaginatedInvoices,
} from "@/types/invoice";

const cleanParams = (params: object) =>
  Object.fromEntries(
    Object.entries(params).filter(
      ([, value]) => value !== undefined && value !== "" && value !== null,
    ),
  );

export const invoicesService = {
  list(filter: InvoiceListFilter): Promise<PaginatedInvoices> {
    return apiClient
      .get<PaginatedInvoices>(URL_CONSTANTS.BILLING.INVOICES, {
        params: cleanParams(filter),
      })
      .then((r) => r.data);
  },

  getById(id: string): Promise<Invoice> {
    return apiClient
      .get<Invoice>(URL_CONSTANTS.BILLING.INVOICE_BY_ID(id))
      .then((r) => r.data);
  },

  downloadDocument(id: string) {
    return apiClient.get<Blob>(URL_CONSTANTS.BILLING.INVOICE_DOCUMENT(id), {
      responseType: "blob",
    });
  },
};
