// ═══════════════════════════════════════════════════════════════════
// 📁 frontend/src/lib/api/legacy.api.ts
// ═══════════════════════════════════════════════════════════════════
// API helper functions for Legacy Certificates module
// ═══════════════════════════════════════════════════════════════════

import { fetchApi } from "./http";

const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || "http://localhost:3007/api";
export const LEGACY_API_BASE = `${API_BASE_URL}/excel`;

// ─── Types ────────────────────────────────────────────────────────────────
export interface LegacyCertificate {
  id: number;
  cert_no: string;
  company_name: string;
  standard: string;
  orginally_reg: string | null;
  issue_date: string | null;
  expire_date: string | null;
  status: string;
  created_at?: string;
  updated_at?: string;
}

export interface LegacyPaginatedResult {
  data: LegacyCertificate[];
  total: number;
  page: number;
  limit: number;
  lastPage: number;
  hasNext: boolean;
  hasPrev: boolean;
}

export interface CreateLegacyDto {
  cert_no: string;
  company_name: string;
  standard: string;
  orginally_reg?: string;
  issue_date?: string;
  expire_date?: string;
  status?: string;
}

export interface UpdateLegacyDto extends Partial<CreateLegacyDto> {}

// ─── List + Search ─────────────────────────────────────────────────────────
export async function getLegacyPaginated(params: {
  page?: number;
  limit?: number;
  q?: string;
  standard?: string;
  status?: string;
  from_date?: string;
  to_date?: string;
}): Promise<LegacyPaginatedResult> {
  const url = new URL(`${LEGACY_API_BASE}/search`);

  // build query params
  url.searchParams.set("page", String(params.page ?? 1));
  url.searchParams.set("limit", String(params.limit ?? 20));
  if (params.q) url.searchParams.set("q", params.q);
  if (params.standard) url.searchParams.set("standard", params.standard);
  if (params.status) url.searchParams.set("status", params.status);
  if (params.from_date) url.searchParams.set("from_date", params.from_date);
  if (params.to_date) url.searchParams.set("to_date", params.to_date);

  return fetchApi<LegacyPaginatedResult>(url.toString().replace(API_BASE_URL, "/api"));
}

// ─── Get single ───────────────────────────────────────────────────────────
export async function getLegacyById(id: number): Promise<LegacyCertificate> {
  return fetchApi<LegacyCertificate>(`${LEGACY_API_BASE}/${id}`);
}

// ─── Add manual ───────────────────────────────────────────────────────────
export async function addManualLegacy(
  dto: CreateLegacyDto,
): Promise<LegacyCertificate> {
  return fetchApi<LegacyCertificate>(`${LEGACY_API_BASE}/manual-add`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(dto),
  });
}

// ─── Update ───────────────────────────────────────────────────────────────
export async function updateLegacy(
  id: number,
  dto: UpdateLegacyDto,
): Promise<LegacyCertificate> {
  return fetchApi<LegacyCertificate>(`${LEGACY_API_BASE}/${id}`, {
    method: "PATCH",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(dto),
  });
}

// ─── Delete ───────────────────────────────────────────────────────────────
export async function deleteLegacy(id: number): Promise<{ message: string }> {
  return fetchApi<{ message: string }>(`${LEGACY_API_BASE}/${id}`, {
    method: "DELETE",
  });
}

// ─── Stats ────────────────────────────────────────────────────────────────
export async function getLegacyStats(): Promise<{
  total: number;
  byStandard: { standard: string; count: number }[];
  byStatus: { status: string; count: number }[];
  recentCount: number;
}> {
  return fetchApi(`${LEGACY_API_BASE}/stats`);
}

// ─── Import Excel ─────────────────────────────────────────────────────────
export async function importLegacyExcel(file: File): Promise<{
  message: string;
  inserted: number;
  skipped: number;
  totalRows: number;
}> {
  const formData = new FormData();
  formData.append("file", file);

  // For file upload we need to use raw fetch (fetchApi may JSON.stringify)
  const token =
    typeof window !== "undefined" ? localStorage.getItem("access_token") : null;

  const res = await fetch(`${LEGACY_API_BASE}/import`, {
    method: "POST",
    headers: token ? { Authorization: `Bearer ${token}` } : undefined,
    body: formData,
  });

  if (!res.ok) {
    const err = await res.json().catch(() => ({ message: "Import failed" }));
    throw new Error(err.message ?? "Import failed");
  }

  return res.json();
}