import { createHash } from "node:crypto";
import type { PoolConnection } from "mysql2/promise";
import { execute, one, pool, query, transaction, type Db, type Row } from "../db/db.js";
import type { Ctx } from "../http/route.js";

export interface Entry { module: string; action: string; entityType?: string; entityId?: string; providerId?: string | null; summary: string; before?: unknown; after?: unknown }
const canonical = (v: unknown): string => JSON.stringify(v, (_k, x: unknown) => (x && typeof x === "object" && !Array.isArray(x) ? Object.fromEntries(Object.entries(x).sort(([a], [b]) => (a < b ? -1 : 1))) : x)) ?? "null";
const sha = (s: string) => createHash("sha256").update(s).digest("hex");
const SECRET = /password|secret|token|hash/i;
const clean = (v: unknown) => (v === undefined ? null : JSON.stringify(v, (k, x: unknown) => (SECRET.test(k) ? "[hidden]" : x)));
const payloadOf = (r: Row) => sha(canonical([r["module"], r["action"], r["entity_type"] ?? null, r["entity_id"] ?? null, r["summary"] ?? null, r["before_json"] ?? null, r["after_json"] ?? null, r["actor_user_id"] ?? null, r["occurred_at"]]));

/** Appends to the tamper-evident chain. The head row is locked, so two writers cannot fork the chain. */
async function append(tx: PoolConnection, projectId: string, who: { userId: string | null; role: string | null; ip: string | null; requestId: string | null }, e: Entry): Promise<void> {
  await execute(tx, "INSERT IGNORE INTO audit_chain_heads (project_id, last_event_id, last_hash) SELECT ?, 0, COALESCE((SELECT chain_hash FROM audit_events_legacy WHERE project_id=? ORDER BY id DESC LIMIT 1), REPEAT('0',64))", [projectId, projectId]);
  const head = (await one(tx, "SELECT last_hash FROM audit_chain_heads WHERE project_id=? FOR UPDATE", [projectId]))!;
  const at = new Date().toISOString();
  const row: Row = { module: e.module, action: e.action, entity_type: e.entityType ?? null, entity_id: e.entityId ?? null, summary: e.summary.slice(0, 255), before_json: clean(e.before), after_json: clean(e.after), actor_user_id: who.userId, occurred_at: at };
  const payload = payloadOf(row), hash = sha(`${head["last_hash"]}:${payload}`);
  const r = await execute(tx, `INSERT INTO audit_events (project_id, occurred_at, actor_user_id, actor_role, ip, request_id, module, action, entity_type, entity_id, provider_id, summary, before_json, after_json, payload_sha256, prev_hash, hash)
    VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, [projectId, at.slice(0, 23).replace("T", " "), who.userId, who.role, who.ip, who.requestId, e.module, e.action, row["entity_type"], row["entity_id"], e.providerId ?? null, row["summary"], row["before_json"], row["after_json"], payload, head["last_hash"], hash]);
  await execute(tx, "UPDATE audit_chain_heads SET last_event_id=?, last_hash=? WHERE project_id=?", [String(r.insertId), hash, projectId]);
}
/** Pass the transaction of the change itself, so the change and its audit record are saved together or not at all. */
export async function audit(db: Db, c: Ctx, e: Entry): Promise<void> {
  const who = { userId: c.user?.id ?? null, role: c.access?.roleCode ?? null, ip: c.ip, requestId: c.req.id };
  const project = c.pid || "1";
  if (db === pool) await transaction((tx) => append(tx, project, who, e)); else await append(db as PoolConnection, project, who, e);
}
export const auditSystem = (projectId: string, e: Entry) => transaction((tx) => append(tx, projectId, { userId: null, role: "system", ip: null, requestId: null }, e));

export async function verifyChain(projectId: string): Promise<{ intact: boolean; checked: number; brokenAt?: string }> {
  let prev: string | null = null, checked = 0, last = "0";
  for (;;) {
    const rows: Row[] = await query(pool, "SELECT * FROM audit_events WHERE project_id=? AND id>? ORDER BY id LIMIT 2000", [projectId, last]);
    if (!rows.length) break;
    for (const r of rows) {
      const ok: boolean = payloadOf(r) === r["payload_sha256"] && sha(`${r["prev_hash"]}:${r["payload_sha256"]}`) === r["hash"] && (prev === null || prev === r["prev_hash"]);
      if (!ok) return { intact: false, checked, brokenAt: String(r["id"]) };
      prev = r["hash"] as string; checked++; last = String(r["id"]);
    }
  }
  const head = await one(pool, "SELECT last_hash FROM audit_chain_heads WHERE project_id=?", [projectId]);
  return head && checked && head["last_hash"] !== prev ? { intact: false, checked, brokenAt: "end of the log" } : { intact: true, checked };
}
