import { createHash } from "node:crypto";
import { audit, verifyChain } from "../../core/audit/audit.js";
import { json, one, pool, query, type Row } from "../../core/db/db.js";
import { storeFile } from "../../core/files/files.js";
import { like, paging, readUpload, type Ctx } from "../../core/http/route.js";
import { defineJob, enqueue } from "../../core/jobs/jobs.js";

export async function events(c: Ctx) {
  const q = c.query, pg = paging(q), where = ["e.project_id=?"], args: string[] = [c.pid];
  if (q["module"]) { where.push("e.module=?"); args.push(q["module"]); }
  if (q["actor"]) { where.push("u.name LIKE ?"); args.push(like(q["actor"])); }
  if (q["q"]) { where.push("(e.summary LIKE ? OR e.action LIKE ?)"); args.push(like(q["q"]), like(q["q"])); }
  if (q["entity"]) { where.push("e.entity_id=?"); args.push(q["entity"]); }
  const range = (col: string) => { const w: string[] = [], a: string[] = []; if (q["from"]) { w.push(`${col}>=?`); a.push(q["from"]); } if (q["to"]) { w.push(`${col}<DATE_ADD(?, INTERVAL 1 DAY)`); a.push(q["to"]); } return { w, a }; };
  const n = range("e.occurred_at"), o = range("e.created_at"), w1 = [...where, ...n.w].join(" AND ");
  const lw = ["e.project_id=?"], la: string[] = [c.pid];
  if (q["module"]) { lw.push("e.module=?"); la.push(q["module"]); }
  if (q["actor"]) { lw.push("u.name LIKE ?"); la.push(like(q["actor"])); }
  if (q["q"]) { lw.push("e.action LIKE ?"); la.push(like(q["q"])); }
  if (q["entity"]) lw.push("1=0");
  const w2 = [...lw, ...o.w].join(" AND "), A = [...args, ...n.a], B = [...la, ...o.a], join = "LEFT JOIN users u ON u.id=e.actor_user_id";
  const t1 = Number((await one(pool, `SELECT COUNT(*) AS n FROM audit_events e ${join} WHERE ${w1}`, A))!["n"]), t2 = Number((await one(pool, `SELECT COUNT(*) AS n FROM audit_events_legacy e ${join} WHERE ${w2}`, B))!["n"]);
  const a = pg.offset < t1 ? await query(pool, `SELECT e.*, u.name AS actor FROM audit_events e ${join} WHERE ${w1} ORDER BY e.id DESC LIMIT ? OFFSET ?`, [...A, pg.pageSize, pg.offset]) : [], left = pg.pageSize - a.length;
  const b = left > 0 ? await query(pool, `SELECT e.id, e.created_at, e.module, e.action, e.source_ref, e.meta, u.name AS actor FROM audit_events_legacy e ${join} WHERE ${w2} ORDER BY e.id DESC LIMIT ? OFFSET ?`, [...B, left, Math.max(0, pg.offset - t1)]) : [];
  return { items: [...a.map((e) => ({ id: e["id"], at: e["occurred_at"], actor: e["actor"] ?? "System", module: e["module"], action: e["action"], entity: [e["entity_type"], e["entity_id"]].filter(Boolean).join(" "), summary: e["summary"] ?? "", before: json<Row | undefined>(e["before_json"], undefined), after: json<Row | undefined>(e["after_json"], undefined), legacy: false })), ...b.map((e) => ({ id: `v1-${e["id"]}`, at: e["created_at"], actor: e["actor"] ?? "System", module: e["module"], action: e["action"], entity: e["source_ref"] ?? "", summary: String(e["action"]).replace(/_/g, " "), after: json<Row | undefined>(e["meta"], undefined), legacy: true }))], page: pg.page, pageSize: pg.pageSize, total: t1 + t2 };
}
export async function verify(c: Ctx) {
  const r = await verifyChain(c.pid), legacy = await one(pool, "SELECT COUNT(*) AS n, SUM(l.chain_hash=e.chain_hash AND l.payload_hash<=>e.payload_hash) AS ok FROM audit_events_legacy l JOIN audit_events_legacy e ON e.id=l.id WHERE l.project_id=?", [c.pid]);
  await audit(pool, c, { module: "audit", action: "verified", summary: r.intact ? `${r.checked} events intact` : `Broken at ${r.brokenAt}` });
  return { ...r, legacyChecked: legacy?.["n"] ?? 0 };
}
export const exportBundle = async (c: Ctx) => ({ jobId: await enqueue(pool, "audit.bundle", {}, { projectId: c.pid, userId: c.user.id }) });
defineJob("audit.bundle", async (job) => {
  const pid = job.projectId!, rows = await query(pool, "SELECT * FROM audit_events WHERE project_id=? ORDER BY id", [pid]), old = await query(pool, "SELECT * FROM audit_events_legacy WHERE project_id=? ORDER BY id", [pid]), body = JSON.stringify({ project: pid, exportedAt: new Date().toISOString(), events: rows, legacy: old }), data = Buffer.from(JSON.stringify({ sha256: createHash("sha256").update(body).digest("hex"), body }));
  const id = await storeFile(pool, { projectId: pid, purpose: "export", name: `audit_bundle_${pid}.json`, data, userId: job.userId, trusted: true });
  return { message: `${rows.length + old.length} events exported.`, href: `/projects/${pid}/files/${id}` };
});
/** Confirms that an exported bundle was not changed after export. */
export async function verifyBundle(c: Ctx) {
  const f = (await readUpload(c)).files[0];
  try { const b = JSON.parse(f!.data.toString("utf8")) as { sha256: string; body: string }; return { valid: createHash("sha256").update(b.body).digest("hex") === b.sha256, events: (JSON.parse(b.body) as { events: unknown[] }).events.length }; } catch { return { valid: false, events: 0 }; }
}
