import {
  DispoStagedRecordType,
  ImportBatchStatus,
  StagedRecordStatus,
} from "@capakraken/db";
import { TRPCError } from "@trpc/server";
import { describe, expect, it } from "vitest";
import {
  assertImportBatchCancelable,
  buildCancelledImportBatchUpdateData,
  buildDispoImportCommitAuditSummary,
  buildResolvedStagedRecordUpdateData,
  resolveDispoStagedRecordStatus,
  resolveDispoStagedRecordStoreKey,
  terminalImportBatchStatuses,
} from "../router/dispo-management-support.js";

describe("dispo management support", () => {
  it("guards terminal import batches from cancellation", () => {
    expect(terminalImportBatchStatuses).toEqual([
      ImportBatchStatus.COMMITTED,
      ImportBatchStatus.CANCELLED,
    ]);

    expect(() => assertImportBatchCancelable({
      id: "batch_1",
      status: ImportBatchStatus.PENDING,
    })).not.toThrow();

    expect(() => assertImportBatchCancelable({
      id: "batch_1",
      status: ImportBatchStatus.CANCELLED,
    })).toThrowError(
      new TRPCError({
        code: "BAD_REQUEST",
        message: 'Cannot cancel batch in status "CANCELLED"',
      }),
    );

    expect(buildCancelledImportBatchUpdateData()).toEqual({
      status: ImportBatchStatus.CANCELLED,
    });
  });

  it("maps staged-record actions and store keys", () => {
    expect(resolveDispoStagedRecordStatus("APPROVE")).toBe(StagedRecordStatus.APPROVED);
    expect(resolveDispoStagedRecordStatus("REJECT")).toBe(StagedRecordStatus.REJECTED);
    expect(resolveDispoStagedRecordStatus("SKIP")).toBe(StagedRecordStatus.REJECTED);

    expect(buildResolvedStagedRecordUpdateData("APPROVE")).toEqual({
      status: StagedRecordStatus.APPROVED,
    });

    expect(resolveDispoStagedRecordStoreKey(DispoStagedRecordType.RESOURCE)).toBe("stagedResource");
    expect(resolveDispoStagedRecordStoreKey(DispoStagedRecordType.AVAILABILITY_RULE)).toBe("stagedAvailabilityRule");
    expect(resolveDispoStagedRecordStoreKey(DispoStagedRecordType.UNRESOLVED)).toBe("stagedUnresolvedRecord");
  });

  it("builds commit audit summaries", () => {
    expect(buildDispoImportCommitAuditSummary({
      created: 4,
      rejected: 1,
    })).toBe('Committed import batch ({"created":4,"rejected":1})');
  });
});
