// 2026-11-11 — Template Content (certification_db.template_contents — the rows printed in the
// Audit Plan time tables of scheme.qrs.ae AND the main CRM job documents)
import { fetchApi, API_BASE_URL } from "@/lib/api/http";

export interface TemplateLite {
  id: number;
  name: string;
  stageName?: string | null;
  stage_name?: string | null;
  isActive?: boolean | number;
  is_active?: boolean | number;
}

export interface TemplateContentRow {
  id: number;
  template_id: number;
  title: string | null;
  content: string | null;
  functional_area: string | null;
  startTime: string | null;
  endTime: string | null;
  updated_at?: string;
}

export type TemplateContentInput = Omit<TemplateContentRow, "id" | "updated_at">;

const BASE = `${API_BASE_URL}/template-contents`;

export async function listTemplatesLite(): Promise<TemplateLite[]> {
  const res = await fetchApi<any>(`${API_BASE_URL}/templates?page=1&limit=500`);
  return Array.isArray(res) ? res : res?.data ?? [];
}
// export const listContents = (templateId: number) => fetchApi<TemplateContentRow[]>(`${BASE}?templateId=${templateId}`);
// ↑ original (2026-11-11 first version) — wrong: GET /template-contents returns rows GROUPED per template:
//   [{ template_id, template_name, schedule: { "09:00:00 - 09:30:00": [row, …], … } }]
// so the rows must be flattened out of `schedule` (same shape scheme.qrs.ae's Template Content page reads).
type ContentGroup = { template_id: number; template_name?: string; schedule?: Record<string, any[]> };
function flatten(res: any): TemplateContentRow[] {
  const groups: ContentGroup[] = Array.isArray(res) ? res : Array.isArray(res?.data) ? res.data : [];
  const out: TemplateContentRow[] = [];
  for (const g of groups) {
    if (g && g.schedule && typeof g.schedule === "object") {
      for (const list of Object.values(g.schedule)) {
        for (const r of list || []) out.push({ ...r, template_id: Number(r.template_id ?? g.template_id) });
      }
    } else if (g && (g as any).id && (g as any).content !== undefined) {
      out.push(g as any); // already a flat row
    }
  }
  return out.sort(
    (a, b) => a.template_id - b.template_id || String(a.startTime ?? "99").localeCompare(String(b.startTime ?? "99")) || a.id - b.id,
  );
}
export const listContents = async (templateId: number) => flatten(await fetchApi<any>(`${BASE}?templateId=${templateId}`));
/** every content row of every template (one call) — for row counts per template */
export const listAllContents = async () => flatten(await fetchApi<any>(BASE));
export const createContent = (body: Partial<TemplateContentInput> & { template_id: number }) =>
  fetchApi<TemplateContentRow>(BASE, { method: "POST", body: JSON.stringify(body) });
export const updateContent = (id: number, body: Partial<TemplateContentInput>) =>
  fetchApi<TemplateContentRow>(`${BASE}/${id}`, { method: "PUT", body: JSON.stringify(body) });
export const deleteContent = (id: number) => fetchApi<any>(`${BASE}/${id}`, { method: "DELETE" });
