import { createCoreAPIClient } from "@/lib/features/coreClient";
import type { CoreResponse } from "@/lib/features/types";

/**
 * Export approval requests.
 *
 * The second export path: instead of downloading, the generated workbook is
 * submitted for a super admin to approve, and emailed to the requester on
 * approval. Direct download is unaffected.
 */

const coreClient = createCoreAPIClient();

const BASE = "/v1/admin-console/export-requests";

export type ExportRequestStatus = "pending" | "approved" | "rejected";

export interface ExportRequest {
  id: string;
  requested_by: string;
  section: string;
  label: string;
  filename: string;
  filters_summary: string | null;
  row_count: number;
  file_size: number;
  status: ExportRequestStatus;
  reviewed_by: string | null;
  reviewed_at: string | null;
  review_note: string | null;
  delivered_at: string | null;
  delivery_error: string | null;
  /**
   * Set once the stored workbook has been deleted, 24 hours after it was emailed.
   * The request and its audit trail remain; only the file is gone.
   */
  file_purged_at: string | null;
  created_at: string;
}

/**
 * Submits a generated workbook for approval.
 *
 * The file is sent base64-encoded in JSON: the console reaches core through its
 * own /api/proxy route, which forwards a JSON body cleanly, and exports are small
 * enough (bounded by MAX_EXPORT_ROWS) that the ~33% encoding overhead is
 * immaterial.
 */
export async function submitExportRequest(body: {
  section: string;
  label: string;
  filename: string;
  filtersSummary?: string;
  rowCount: number;
  fileBase64: string;
}): Promise<CoreResponse<ExportRequest>> {
  return await coreClient<ExportRequest>(BASE, {
    method: "POST",
    body: JSON.stringify(body),
  });
}

/** The whole queue for a super admin; the caller's own requests otherwise. */
export async function listExportRequests(
  query?: { status?: ExportRequestStatus; limit?: number; offset?: number },
  headers?: HeadersInit,
): Promise<
  CoreResponse<{ items: ExportRequest[]; total: number; canReview: boolean }>
> {
  const params = new URLSearchParams();
  if (query?.status) params.set("status", query.status);
  if (query?.limit) params.set("limit", String(query.limit));
  if (query?.offset) params.set("offset", String(query.offset));
  const qs = params.toString();
  return await coreClient(`${BASE}${qs ? `?${qs}` : ""}`, {
    method: "GET",
    headers,
  });
}

/**
 * Browser URL for the stored workbook.
 *
 * Points at the console's own proxy rather than core, so the request carries the
 * session cookies and picks up the server-side API key on the way through — the
 * same hop every other call to core uses. Returned as a URL rather than fetched
 * because this is handed to an anchor: the browser then streams the file straight to
 * disk and honours `Content-Disposition`, instead of the workbook passing through JS
 * memory as a blob.
 *
 * Core decides who may fetch it — any request for a super admin, and the caller's
 * own only once approved.
 */
export function exportRequestFileUrl(id: string): string {
  return `/api/proxy${BASE}/${encodeURIComponent(id)}/file`;
}

/** Super-admin only; core returns 403 for anyone else. */
export async function reviewExportRequest(
  id: string,
  action: "approve" | "reject",
  note?: string,
): Promise<CoreResponse<ExportRequest>> {
  return await coreClient<ExportRequest>(`${BASE}/${id}/review`, {
    method: "POST",
    body: JSON.stringify({ action, note }),
  });
}
