import { randomUUID } from "node:crypto";
import { mkdirSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { tmpdir } from "node:os";

import { expect, it, vi } from "vitest";

import { ManagedStorage } from "../../apps/api/src/managed-storage.js";
import { WorkerAiCallGate } from "../../apps/worker/src/ai-call-gate.js";
import { WorkerStorageStatus } from "../../apps/worker/src/storage-status.js";
import { StructuredJsonlLogger } from "../../apps/worker/src/structured-log.js";

it("TDD-WP0-LOG-001 blocks AI before an upstream call when logging becomes unavailable", async () => {
  const root = join(tmpdir(), `dada-wp0-08-worker-${randomUUID()}`);
  mkdirSync(root, { recursive: true });
  const blockedDirectory = join(root, "blocked-log-directory");
  writeFileSync(blockedDirectory, "not-a-directory");
  const databasePath = join(root, "db", "dada.sqlite3");
  const managedStorage = new ManagedStorage({ dataRoot: root, databasePath });
  const workerStorage = new WorkerStorageStatus(databasePath);
  let storageStatus: "active" | "unavailable" = "active";
  const logger = new StructuredJsonlLogger({
    component: "worker",
    directory: blockedDirectory,
    onWriteFailure: () => {
      storageStatus = "unavailable";
      workerStorage.markLogUnavailable();
    },
  });
  const externalCall = vi.fn(async () => ({ provider_request_id: "must-not-exist" }));
  const gate = new WorkerAiCallGate({ getStorageStatus: () => storageStatus, logger });

  await expect(gate.execute("corr_worker_log_failure", "job_internal", externalCall)).resolves.toEqual({
    reason: "storage_unavailable",
    status: "blocked",
  });
  expect(storageStatus).toBe("unavailable");
  expect(workerStorage.getStatus()).toBe("unavailable");
  expect(managedStorage.getState().storage_status).toBe("unavailable");
  expect(externalCall).not.toHaveBeenCalled();

  const directory = process.env.DADA_EVIDENCE_DIR_LOG;
  if (directory) {
    mkdirSync(directory, { recursive: true });
    writeFileSync(join(directory, "external-calls.json"), `${JSON.stringify({ calls: 0, reason: "storage_unavailable", status: "passed" }, null, 2)}\n`);
  }

  const { rm } = await import("node:fs/promises");
  workerStorage.close();
  managedStorage.close();
  await rm(root, { force: true, recursive: true });
});
