
const API_BASE =
  (typeof process !== 'undefined' && process.env.NEXT_PUBLIC_API_URL) || '/api';

function authHeaders(): Record<string, string> {
  if (typeof window === 'undefined') return {};
  // Adjust the key if your token is stored under a different name.
  const token =
    localStorage.getItem('token') ||
    localStorage.getItem('access_token') ||
    '';
  return token ? { Authorization: `Bearer ${token}` } : {};
}

async function request<T>(path: string): Promise<T> {
  const res = await fetch(`${API_BASE}${path}`, {
    method: 'GET',
    headers: { 'Content-Type': 'application/json', ...authHeaders() },
    credentials: 'include',
  });
  if (!res.ok) {
    let msg = `Request failed (${res.status})`;
    try {
      const j = await res.json();
      msg = j?.message || msg;
    } catch {
      /* ignore */
    }
    throw new Error(msg);
  }
  return res.json() as Promise<T>;
}

// ── types (mirror backend AuditDetail* shapes) ──
export type AuditType = 'Initial' | 'Surveillance' | 'Recertification';

export interface AuditDetailFilters {
  source?: 'QRS' | 'TQS' | 'QRS & TQS' | 'all';
  audit_type?: AuditType;
  year?: string;
  month?: string; // '1'..'12'
  report_status?: 's1_missing' | 's2_missing' | 's1_uploaded' | 's2_uploaded';
  phase?: 'conducted' | 'upcoming';
  auditor?: string;
  search?: string;
  sort?: 'audit_date' | 'client' | 'auditor' | 'type';
  dir?: 'asc' | 'desc';
  page?: number;
  limit?: number;
}

export interface AuditDetailRow {
  record_id: number;
  source: 'QRS' | 'TQS' | 'QRS & TQS';
  table: string;
  client_name: string | null;
  audit_date: string | null;
  year: string | null;
  month: string | null;
  audit_type: AuditType;
  stage1_uploaded: boolean;
  stage1_path: string | null;
  stage2_uploaded: boolean;
  stage2_path: string | null;
  attendance_uploaded: boolean;
  attendance_path: string | null;
  support_uploaded: boolean;
  support_path: string | null;
  auditor_id: number;
  auditor: string;
  age_days: number | null;
  conducted: boolean;
}

export interface AuditDetailResponse {
  rows: AuditDetailRow[];
  total: number;
  page: number;
  limit: number;
  totalPages: number;
  can_manage?: boolean;   // 🆕

  summary: {
    total_audits: number;
    stage1_missing: number;
    stage2_missing: number;
    total_assigned: number;
    conducted_count: number;
    scheduled_count: number;
    total_completed: number;
    stage1_uploaded: number;
    stage2_uploaded: number;
    initial_count: number;
    initial_completed: number;
    surveillance_count: number;
    surveillance_completed: number;
    recert_count: number;
    recert_completed: number;
  };
  aging: {
    bucket_0_30: number;
    bucket_31_60: number;
    bucket_61_90: number;
    bucket_90_plus: number;
  };
}

function toQuery(f: AuditDetailFilters): string {
  const p = new URLSearchParams();
  Object.entries(f).forEach(([k, v]) => {
    if (v !== undefined && v !== null && v !== '') p.set(k, String(v));
  });
  const s = p.toString();
  return s ? `?${s}` : '';
}

/** Paginated detail report + summary + aging. */
export function getAuditDetailReport(
  f: AuditDetailFilters = {},
): Promise<AuditDetailResponse> {
  return request<AuditDetailResponse>(`/audit-report/detail${toQuery(f)}`);
}

/** Public URL of a stage report file (Strategy A — open in a new tab). */
export function getAuditReportFileUrl(params: {
  source: 'QRS' | 'TQS';
  table: string;
  id: number;
  stage: 1 | 2;
}): Promise<{ url: string; filename: string }> {
  const q = new URLSearchParams({
    source: params.source,
    table: params.table,
    id: String(params.id),
    stage: String(params.stage),
  }).toString();
  return request<{ url: string; filename: string }>(
    `/audit-report/file/url?${q}`,
  );
}

/**
 * Fetch every row that matches the filters (no pagination) by looping the
 * paginated endpoint. Used by the Excel / PDF exporters so they cover the
 * full filtered set, not just the visible page.
 */
export async function getAllAuditDetailRows(
  f: AuditDetailFilters = {},
): Promise<AuditDetailRow[]> {
  const first = await getAuditDetailReport({ ...f, page: 1, limit: 200 });
  let all = [...first.rows];
  for (let p = 2; p <= first.totalPages; p++) {
    const next = await getAuditDetailReport({ ...f, page: p, limit: 200 });
    all = all.concat(next.rows);
  }
  return all;
}

/**
 * Download the professional server-generated report (Excel or PDF).
 * Hits /audit-report/export/{excel|pdf} with the current filters, gets the
 * file as a blob, and triggers a browser download. The backend builds the
 * branded workbook/document (ExcelJS / PDFKit).
 */
export async function downloadAuditReport(
  format: 'excel' | 'pdf',
  f: AuditDetailFilters = {},
): Promise<void> {
  const res = await fetch(`${API_BASE}/audit-report/export/${format}${toQuery(f)}`, {
    method: 'GET',
    headers: { ...authHeaders() },
    credentials: 'include',
  });
  if (!res.ok) {
    let msg = `Export failed (${res.status})`;
    try {
      const j = await res.json();
      msg = j?.message || msg;
    } catch {
      /* ignore */
    }
    throw new Error(msg);
  }
  const blob = await res.blob();
  const url = URL.createObjectURL(blob);
  const ext = format === 'excel' ? 'xlsx' : 'pdf';
  const a = document.createElement('a');
  a.href = url;
  a.download = `audit-report-${new Date().toISOString().slice(0, 10)}.${ext}`;
  document.body.appendChild(a);
  a.click();
  a.remove();
  setTimeout(() => URL.revokeObjectURL(url), 10_000);
}
// ═══════════════════════════════════════════════════════════════════════
// 🆕 AUDIT ASSISTANT (AI agent endpoint)
// ═══════════════════════════════════════════════════════════════════════

export interface AssistantMessage {
  role: 'user' | 'assistant';
  content: string;
}

/** Ask the AI audit assistant a question. Sends the prior turns as history. */
export async function askAuditAssistant(
  message: string,
  history: AssistantMessage[] = [],
): Promise<{ answer: string; download?: { format: 'excel' | 'pdf'; filters: AuditDetailFilters } }> {
  const res = await fetch(`${API_BASE}/audit-report/assistant`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json', ...authHeaders() },
    credentials: 'include',
    body: JSON.stringify({ message, history }),
  });
  if (!res.ok) {
    let msg = `Assistant failed (${res.status})`;
    try { msg = (await res.json())?.message || msg; } catch { }
    throw new Error(msg);
  }
  return res.json();
}
/** 🆕 Transfer an audit to another auditor (admins only). */
export async function transferAudit(payload: {
  source: 'QRS' | 'TQS' | 'QRS & TQS';
  table?: string;
  record_id: number;
  from_auditor_id: number;
  to_user_id: number;
}): Promise<{ ok: boolean }> {
  const res = await fetch(`${API_BASE}/audit-report/transfer`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json', ...authHeaders() },
    credentials: 'include',
    body: JSON.stringify(payload),
  });
  if (!res.ok) {
    let msg = `Transfer failed (${res.status})`;
    try { msg = (await res.json())?.message || msg; } catch {}
    throw new Error(msg);
  }
  return res.json();
}
/** 🆕 Users an audit can be transferred to (admins only). */
export function getTransferAuditors(): Promise<{ user_id: number; name: string; email: string }[]> {
  return request<{ user_id: number; name: string; email: string }[]>(`/audit-report/auditors`);
}