import type { AlqoveClient } from '../client';
import type { LedgerEntry, ListLedgerInput, PaginatedLedgerResponse } from './admin-financials';

export type { LedgerEntry, ListLedgerInput, PaginatedLedgerResponse } from './admin-financials';

export interface ExportCsvInput {
  from?: string;
  to?: string;
}

/**
 * Seller-facing statements / ledger endpoints. The CSV export is handled via
 * `downloadCsv()` rather than a plain `<a href>` link because the API uses
 * bearer-token-in-header auth — a navigational link would not carry the
 * `Authorization` header and the request would 401. `downloadCsv()` fetches
 * the streamed CSV as a Blob, threading the token through, and the UI is
 * expected to wrap the resulting Blob in an object URL + programmatic
 * `<a download>` click.
 *
 * `exportCsvUrl()` is exposed alongside for debugging / SSR-only contexts
 * where a session cookie happens to be in play; it is not the recommended UI
 * entry point.
 */
export function createStatementsEndpoints(client: AlqoveClient) {
  function buildExportSuffix(params: ExportCsvInput): string {
    const qs = new URLSearchParams();
    if (params.from) qs.set('from', params.from);
    if (params.to) qs.set('to', params.to);
    return qs.toString() ? `?${qs.toString()}` : '';
  }

  return {
    listForStore(storeId: string, params: ListLedgerInput = {}) {
      const qs = new URLSearchParams();
      if (params.page) qs.set('page', String(params.page));
      if (params.per_page) qs.set('per_page', String(params.per_page));
      if (params.from) qs.set('from', params.from);
      if (params.to) qs.set('to', params.to);
      const suffix = qs.toString() ? `?${qs.toString()}` : '';
      return client.get<PaginatedLedgerResponse>(
        `/v1/stores/${storeId}/ledger${suffix}`,
      );
    },

    /**
     * Absolute URL for the CSV export endpoint. Useful for logging/debugging.
     * For end-user downloads, prefer `downloadCsv()` — a plain navigational
     * link cannot send the bearer Authorization header.
     */
    exportCsvUrl(storeId: string, params: ExportCsvInput = {}): string {
      const suffix = buildExportSuffix(params);
      return `${client.baseUrl}/v1/stores/${storeId}/statements/export.csv${suffix}`;
    },

    /**
     * Fetches the CSV export as a `Blob`, threading the bearer token through
     * `Authorization`. The UI wraps the blob in an object URL and triggers a
     * programmatic download.
     */
    downloadCsv(storeId: string, params: ExportCsvInput = {}): Promise<Blob> {
      const suffix = buildExportSuffix(params);
      return client.getBlob(`/v1/stores/${storeId}/statements/export.csv${suffix}`);
    },
  };
}

// Re-export LedgerEntry alongside the factory so consumers can import from a
// single module without crossing into admin-financials.
export type LedgerEntryRow = LedgerEntry;
