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

import { afterEach, describe, expect, it } from "vitest";

import { RegistrationService } from "../../apps/api/src/registration.js";
import { MockResendAdapter } from "../../apps/api/src/resend-adapter.js";
import { GatewayBalanceRuntime } from "../../apps/worker/src/gateway-balance-runtime.js";

const roots: string[] = [];
const closeables: Array<{ close(): void }> = [];
const now = Date.parse("2026-08-02T15:00:00.000Z");

afterEach(() => {
  for (const closeable of closeables.splice(0).reverse()) closeable.close();
  for (const root of roots.splice(0)) rmSync(root, { force: true, recursive: true });
});

describe("TASK-WP3-02 worker recovery boundary", () => {
  it("does not auto-restore a balance block before a confirmed recovery", () => {
    const root = mkdtempSync(join(tmpdir(), "dada-wp3-02-worker-"));
    roots.push(root);
    const registration = new RegistrationService({
      challengePepper: Buffer.alloc(32, 0xa1), clock: () => now,
      currentPrivacyNoticeVersion: "p0a-registration-notice-v1", databasePath: join(root, "dada.sqlite3"),
      invitePepper: Buffer.alloc(32, 0xa2), resend: new MockResendAdapter(), sessionPepper: Buffer.alloc(32, 0xa3),
    });
    closeables.push(registration);
    const runtime = new GatewayBalanceRuntime({ clock: () => now, database: registration.database });
    closeables.push(runtime);
    runtime.seedModels([{ gatewayAccountRef: "gateway-account-primary", modelId: "gemini-3.1-flash-image-preview" }]);
    runtime.recordInsufficient({ eventId: randomUUID(), gatewayAccountRef: "gateway-account-primary", impactScope: "model", modelId: "gemini-3.1-flash-image-preview", sourceCategory: "adapter_balance_signal" });
    expect(() => runtime.restoreWithoutConfirmedRecovery("gateway-account-primary", randomUUID())).toThrow("gateway_balance_recovery_unconfirmed");
    expect(runtime.readState("gateway-account-primary")).toMatchObject({ recoveryStatus: "awaiting_confirmation" });
  });
});
