/**
 * RESTART-SURVIVAL verify — shift-handover externalisation.
 *
 * Two invocations of this script are two separate PROCESSES sharing one DB. That is exactly a
 * restart: a fresh process reading what a dead one wrote. Because the module is DB-authoritative
 * (no in-memory store), the handover must come back.
 *
 *   create        create a handover, add a dated open item + an escalation, submit + acknowledge;
 *                 print its id. Exercises every write path + nested JSON + Date fields.
 *   read <id>     (FRESH PROCESS) read it back and assert it survived intact, with real Dates.
 */
import {
  createHandover, addOpenItem, addEscalation, submitHandover, acknowledgeHandover,
  getHandover, getHandoverReport,
} from "../server/lib/shift-handover";

async function create() {
  const h = await createHandover({ shiftType: "NIGHT", outgoingAnalyst: "Verify Analyst", notes: "restart-survival test" });
  await addOpenItem(h.id, {
    priority: "CRITICAL", type: "INCIDENT", title: "Brute-force on VPN gateway",
    description: "Ongoing; blocklist applied", status: "IN_PROGRESS",
    dueDate: new Date("2026-08-01T00:00:00.000Z"),
  });
  await addEscalation(h.id, {
    severity: "HIGH", title: "Possible lateral movement",
    description: "Escalated to Tier 3", escalatedTo: "tier3-oncall", status: "OPEN",
  });
  await submitHandover(h.id);
  await acknowledgeHandover(h.id, "Incoming Analyst", "Received, taking over");
  console.log(JSON.stringify({ mode: "create", id: h.id }));
}

async function read(id: string) {
  const h = await getHandover(id);
  const report = await getHandoverReport(id); // throws if any nested Date came back as a string
  const checks = {
    present: !!h,
    status_ACKNOWLEDGED: h?.status === "ACKNOWLEDGED",
    openItem_survived: h?.openItems.length === 1 && h.openItems[0].title === "Brute-force on VPN gateway",
    openItem_dueDate_is_Date: h?.openItems[0]?.dueDate instanceof Date,
    escalation_survived: h?.escalations.length === 1 && h.escalations[0].escalatedTo === "tier3-oncall",
    escalation_escalatedAt_is_Date: h?.escalations[0]?.escalatedAt instanceof Date,
    ack_survived: h?.acknowledgement?.acknowledgedBy === "Incoming Analyst",
    ack_acknowledgedAt_is_Date: h?.acknowledgement?.acknowledgedAt instanceof Date,
    report_rendered: typeof report === "string" && report.includes("Brute-force on VPN gateway"),
  };
  const pass = Object.values(checks).every(Boolean);
  console.log(JSON.stringify({ mode: "read", id, pass, checks }));
  process.exit(pass ? 0 : 1);
}

const [cmd, arg] = process.argv.slice(2);
(cmd === "read" ? read(arg) : create()).catch((e) => {
  console.error("VERIFY ERROR:", e?.message || e);
  process.exit(2);
});
