import { URL_CONSTANTS } from "@/constants/URLS";
import { client } from "../utils/api";
import type {
  InitiateResponse,
  PaymentMethod,
  PaymentPlatform,
} from "./payments.service";

const W = URL_CONSTANTS.WAREHOUSE_INVOICES;

/**
 * A warehouse fee invoice as the freight API projects it for the customer
 * (the historical `WarehouseFeeInvoice` view shape — a subset is used here).
 */
export interface PortalWarehouseInvoice {
  id: string;
  invoiceNumber: string;
  invoiceType: string;
  status: string;
  currency: string;
  totalAmount: number | string;
  paidAmount: number | string;
  balanceAmount: number | string;
  issuedAt?: string | null;
  dueDate?: string | null;
  paidAt?: string | null;
  bookingId?: string | null;
  inventoryId?: string | null;
  bookingReference?: string | null;
  inventoryReference?: string | null;
  cargoDescription?: string | null;
  containerNumber?: string | null;
}

export const warehouseInvoicesService = {
  /** Warehouse fee invoices linked to a booking (via its inventory items). */
  listForBooking: async (bookingId: string): Promise<PortalWarehouseInvoice[]> => {
    const { data } = await client.get(W.FOR_BOOKING(bookingId));
    return data.data ?? data;
  },

  /** A single warehouse fee invoice (carries `bookingId` for source linking). */
  get: async (id: string): Promise<PortalWarehouseInvoice> => {
    const { data } = await client.get(W.BY_ID(id));
    return data.data ?? data;
  },

  /** The sealed warehouse fee invoice PDF. */
  downloadDocument: async (id: string): Promise<Blob> => {
    const { data } = await client.get(W.DOCUMENT(id), { responseType: "blob" });
    return data;
  },

  /** The sealed warehouse fee payment receipt PDF (available once paid). */
  downloadReceipt: async (id: string): Promise<Blob> => {
    const { data } = await client.get(W.RECEIPT(id), { responseType: "blob" });
    return data;
  },

  /**
   * Initiate a Telebirr/Waafi online payment for a warehouse demurrage/storage
   * invoice. Returns the payment intent + `clientAction` to redirect the browser
   * to the provider (mirrors the booking `/pay` flow). The backoffice cash
   * `/pay` (record-a-payment) path is unaffected.
   */
  payOnline: async (
    id: string,
    payload: {
      method: PaymentMethod;
      platform?: PaymentPlatform;
      payerAccount?: string;
      returnUrl?: string;
      failureUrl?: string;
    },
  ): Promise<InitiateResponse> => {
    const { data } = await client.post(W.PAY_ONLINE(id), {
      platform: "web",
      ...payload,
    });
    return data.data ?? data;
  },
};
