// ═══════════════════════════════════════════════════════════════
//  lib/api/checklist.api.ts
//
// Matches the confirmed real convention seen in audit-request.api.ts:
// each module gets its own dedicated api.ts exporting a base URL
// constant plus typed functions, rather than components calling
// fetchApi() directly with raw strings scattered around the UI.
// ═══════════════════════════════════════════════════════════════

import { fetchApi, API_BASE_URL } from "./http";
import type {
  ChecklistTemplate,
  AuditChecklistItem,
  AuditChecklistFull,
  BuildChecklistDto,
  CreateTemplateDto,
  UpdateTemplateDto,
  ReviewItemDto,
  NotifyClientDto,
} from "./types/checklist.types";

export const CHECKLIST_API_BASE_URL = API_BASE_URL;

// ── Template management (admin templates page) ───────────────────
export async function listChecklistTemplates(
  params?: { onlyMine?: boolean },
): Promise<ChecklistTemplate[]> {
  const qs = params?.onlyMine ? "?onlyMine=1" : "";
  const res = await fetchApi<ChecklistTemplate[] | { data: ChecklistTemplate[] }>(
    `${API_BASE_URL}/checklist-templates${qs}`,
    { method: "GET" },
  );
  return Array.isArray(res) ? res : res.data ?? [];
}

export async function createChecklistTemplate(dto: CreateTemplateDto): Promise<ChecklistTemplate> {
  return fetchApi<ChecklistTemplate>(`${CHECKLIST_API_BASE_URL}/checklist-templates`, {
    method: "POST",
    body: JSON.stringify(dto),
  });
}

export async function updateChecklistTemplate(id: number, dto: UpdateTemplateDto): Promise<ChecklistTemplate> {
  return fetchApi<ChecklistTemplate>(`${CHECKLIST_API_BASE_URL}/checklist-templates/${id}`, {
    method: "PATCH",
    body: JSON.stringify(dto),
  });
}

export async function deleteChecklistTemplate(id: number): Promise<void> {
  await fetchApi(`${CHECKLIST_API_BASE_URL}/checklist-templates/${id}`, { method: "DELETE" });
}

// ── Auditor workspace tab ─────────────────────────────────────────
export async function getAvailableChecklistTemplates(auditScheduleRowId: number): Promise<ChecklistTemplate[]> {
  const res = await fetchApi<ChecklistTemplate[] | { data: ChecklistTemplate[] }>(
    `${CHECKLIST_API_BASE_URL}/audits/${auditScheduleRowId}/checklist/available-templates`,
    { method: "GET" },
  );
  return Array.isArray(res) ? res : res.data || [];
}

export async function getAuditorChecklist(auditScheduleRowId: number): Promise<AuditChecklistItem[]> {
  const res = await fetchApi<AuditChecklistItem[] | { data: AuditChecklistItem[] }>(
    `${CHECKLIST_API_BASE_URL}/audits/${auditScheduleRowId}/checklist`,
    { method: "GET" },
  );
  return Array.isArray(res) ? res : res.data || [];
}

export async function buildChecklist(auditScheduleRowId: number, dto: BuildChecklistDto): Promise<{ id: number }> {
  return fetchApi<{ id: number }>(`${CHECKLIST_API_BASE_URL}/audits/${auditScheduleRowId}/checklist/build`, {
    method: "POST",
    body: JSON.stringify(dto),
  });
}

export async function submitChecklist(checklistId: number): Promise<void> {
  await fetchApi(`${CHECKLIST_API_BASE_URL}/checklists/${checklistId}/submit`, { method: "POST" });
}

/** Notify the client: multiple emails (auto-fetched on the frontend but
 *  editable), optional message + due date. Backend sends one branded email
 *  per address plus a real-time notification on the client portal. */
export async function notifyClientOfChecklist(checklistId: number, dto: NotifyClientDto): Promise<AuditChecklistFull> {
  return fetchApi<AuditChecklistFull>(`${CHECKLIST_API_BASE_URL}/checklists/${checklistId}/notify-client`, {
    method: "POST",
    body: JSON.stringify(dto),
  });
}

/** Grouped read: every checklist on this audit (one per standard) with
 *  items, uploader/reviewer names and lifecycle stamps. */
export async function getAuditChecklists(auditScheduleRowId: number): Promise<AuditChecklistFull[]> {
  const res = await fetchApi<AuditChecklistFull[] | { data: AuditChecklistFull[] }>(
    `${CHECKLIST_API_BASE_URL}/audits/${auditScheduleRowId}/checklists`,
    { method: "GET" },
  );
  return Array.isArray(res) ? res : res.data || [];
}

/** Draft only - discard so the auditor can re-select items. */
export async function discardChecklistDraft(checklistId: number): Promise<void> {
  await fetchApi(`${CHECKLIST_API_BASE_URL}/checklists/${checklistId}`, { method: "DELETE" });
}

/** ONE batched review-result notification (rejections list, or
 *  "all approved") - email + real-time on the client portal. */
export async function notifyChecklistReviewResult(checklistId: number): Promise<void> {
  await fetchApi(`${CHECKLIST_API_BASE_URL}/checklists/${checklistId}/notify-review`, { method: "POST" });
}

/** Open the checklist itself as a PDF (server-rendered — the same file
 *  attached to the client's notification email). */
export async function openChecklistPdf(checklistId: number): Promise<void> {
  const token =
    typeof window !== "undefined"
      ? localStorage.getItem("access_token") || sessionStorage.getItem("access_token")
      : null;
  const res = await fetch(`${CHECKLIST_API_BASE_URL}/checklists/${checklistId}/pdf`, {
    credentials: "include",
    headers: token ? { Authorization: `Bearer ${token}` } : {},
  });
  if (!res.ok) throw new Error("Could not load the checklist PDF.");
  const blob = await res.blob();
  const url = URL.createObjectURL(blob);
  window.open(url, "_blank", "noopener");
  setTimeout(() => URL.revokeObjectURL(url), 60_000);
}

/** Open an uploaded document in a new tab. Plain <a href> can't carry the
 *  Bearer token, so fetch as a blob first. */
export async function openChecklistItemDocument(itemId: number): Promise<void> {
  const token =
    typeof window !== "undefined"
      ? localStorage.getItem("access_token") || sessionStorage.getItem("access_token")
      : null;
  const res = await fetch(`${CHECKLIST_API_BASE_URL}/checklists/items/${itemId}/document`, {
    credentials: "include",
    headers: token ? { Authorization: `Bearer ${token}` } : {},
  });
  if (!res.ok) throw new Error("Could not load the document.");
  const blob = await res.blob();
  const url = URL.createObjectURL(blob);
  window.open(url, "_blank", "noopener");
  setTimeout(() => URL.revokeObjectURL(url), 60_000);
}

export async function reviewChecklistItem(itemId: number, dto: ReviewItemDto): Promise<AuditChecklistItem> {
  return fetchApi<AuditChecklistItem>(`${CHECKLIST_API_BASE_URL}/checklists/items/${itemId}/review`, {
    method: "POST",
    body: JSON.stringify(dto),
  });
}

export async function notifyClientOfRejections(checklistId: number): Promise<void> {
  await fetchApi(`${CHECKLIST_API_BASE_URL}/checklists/${checklistId}/notify-rejections`, { method: "POST" });
}
