import { NextResponse } from "next/server";
import { pool } from "@/lib/mysql";
import { audits as defaults, type AuditItem } from "@/app/audit-data";
import type { RowDataPacket } from "mysql2";

type AuditRow = RowDataPacket & {
  audit_id: number; department: string; name: string; frequency: string;
  cqc_key: AuditItem["cqc"]; status: AuditItem["status"]; due_label: string;
  score: number | null; is_draft: number;
};

export async function GET() {
  await pool.query(
    `INSERT IGNORE INTO audit_settings
      (audit_id, department, name, frequency, cqc_key, status, due_label, score, is_draft)
     VALUES ?`,
    [defaults.map(a => [a.id, a.department, a.name, a.frequency, a.cqc, a.status, a.due, a.score ?? null, a.draft ? 1 : 0])],
  );
  const [rows] = await pool.query<AuditRow[]>("SELECT * FROM audit_settings ORDER BY audit_id");
  return NextResponse.json(rows.map(row => ({
    id: row.audit_id, department: row.department, name: row.name,
    frequency: row.frequency, cqc: row.cqc_key, status: row.status,
    due: row.due_label, score: row.score ?? undefined, draft: Boolean(row.is_draft),
  })));
}

export async function PATCH(request: Request) {
  const body = await request.json() as { id?: number; patch?: Partial<AuditItem> };
  if (!body.id || !body.patch) return NextResponse.json({ error: "Invalid audit update" }, { status: 400 });
  const allowed: Record<string, string> = {
    frequency: "frequency", cqc: "cqc_key", status: "status", due: "due_label", score: "score", draft: "is_draft",
  };
  const entries = Object.entries(body.patch).filter(([key]) => allowed[key]);
  if (!entries.length) return NextResponse.json({ ok: true });
  const clauses = entries.map(([key]) => `\`${allowed[key]}\` = ?`).join(", ");
  const values = entries.map(([key, value]) => key === "draft" ? (value ? 1 : 0) : value ?? null);
  await pool.execute(`UPDATE audit_settings SET ${clauses} WHERE audit_id = ?`, [...values, body.id]);
  return NextResponse.json({ ok: true });
}

