// Aging Analysis — API helpers, types, and shared query builder
// Mirrors the auth/blob-download pattern used in CertificateRow.tsx

export const API_BASE_URL =
  process.env.NEXT_PUBLIC_API_URL || "https://web.qrsyst.com/api";

// ── Types (match the backend AgingReport shape) ──
export type CategoryFilter =
  | "all"
  | "recertification"
  | "surveillance"
  | "surveillance1"
  | "surveillance2";

export type SourceFilter = "all" | "Manual" | "new";

export interface AgingFilters {
  year: number;
  months: number[]; // 1-12; empty = all months
  category: CategoryFilter;
  source: SourceFilter;
}

export interface AgingSummary {
  total: number;
  bySource: Record<string, number>;
  byBucket: Record<string, number>;
  byCategory: Record<string, number>;
  byStandard: Record<string, number>;
  byIssueYear: Record<string, number>;
  expired: number;
  expiringWithin90: number;
  undatedSkipped: number;
}

export interface AgingMeta {
  from_year: number;
  to_year: number;
  period_label: string;
  category?: string;
  source_filter: string;
  as_of: string;
  generated_at: string;
  buckets: string[];
}

export interface AgingRow {
  source: string;
  certificate_no: string;
  company_name: string;
  standard: string;
  cert_type: string | null;
  category: string;
  status: string;
  originally_registered: string | null;
  issue_date: string | null;
  expire_date: string | null;
  issue_year: number | null;
  age_days: number | null;
  age_years: number | null;
  days_to_expiry: number | null;
  aging_bucket: string;
  expiry_status: string;
}

export interface AgingReport {
  meta: AgingMeta;
  summary: AgingSummary;
  rows: AgingRow[];
}

// ── Auth token (same keys used across the app) ──
function getToken(): string | null {
  if (typeof window === "undefined") return null;
  return (
    localStorage.getItem("access_token") ||
    localStorage.getItem("token") ||
    sessionStorage.getItem("access_token")
  );
}

// ── Build the query string shared by JSON + export endpoints ──
export function buildAgingQuery(f: AgingFilters): string {
  const p = new URLSearchParams();
  p.set("mode", "cycle");
  p.set("year", String(f.year));
  if (f.months.length > 0 && f.months.length < 12) {
    p.set("months", [...f.months].sort((a, b) => a - b).join(","));
  }
  if (f.category !== "all") p.set("category", f.category);
  if (f.source !== "all") p.set("source", f.source);
  return p.toString();
}

// ── Fetch the JSON report (summary cards) ──
export async function fetchAgingReport(
  f: AgingFilters,
): Promise<AgingReport> {
  const token = getToken();
  const res = await fetch(
    `${API_BASE_URL}/reports/aging-analysis?${buildAgingQuery(f)}`,
    {
      method: "GET",
      headers: { ...(token ? { Authorization: `Bearer ${token}` } : {}) },
      credentials: "include",
    },
  );
  if (!res.ok) throw new Error(`Request failed: ${res.status}`);
  return res.json();
}

// ── Download a file (PDF/Excel) as an authed blob ──
export async function downloadAgingFile(
  kind: "pdf" | "excel",
  f: AgingFilters,
  fileName: string,
): Promise<void> {
  const token = getToken();
  const res = await fetch(
    `${API_BASE_URL}/reports/aging-analysis/export/${kind}?${buildAgingQuery(f)}`,
    {
      method: "GET",
      headers: { ...(token ? { Authorization: `Bearer ${token}` } : {}) },
      credentials: "include",
    },
  );
  if (!res.ok) throw new Error(`Download failed: ${res.status}`);

  const blob = await res.blob();
  const link = document.createElement("a");
  link.href = URL.createObjectURL(blob);
  link.download = fileName;
  link.click();
  URL.revokeObjectURL(link.href);
}

// ── Nice download filename from the current filters/report ──
export function buildFileName(
  kind: "pdf" | "excel",
  f: AgingFilters,
  report: AgingReport | null,
): string {
  const ext = kind === "pdf" ? "pdf" : "xlsx";
  const slug = (s: string) =>
    s.replace(/[^a-z0-9]+/gi, "-").replace(/^-|-$/g, "").toLowerCase();

  const scope =
    report?.meta.category
      ? slug(report.meta.category)
      : f.source === "Manual"
        ? "manual"
        : f.source === "new"
          ? "qrs-tqs"
          : "all-sources";

  const period = report?.meta.period_label
    ? slug(report.meta.period_label)
    : String(f.year);

  return `aging-analysis_${scope}_${period}.${ext}`;
}
