import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import { PolicyNotFoundError, InvalidStateError, UnauthorizedError } from "../lib/errors.generated";
import { draftPolicy, activePolicy, inactivePolicy } from "../testing/fixtures";
import { run } from "./deleteAuditPolicy";
import { deleteAuditPolicy } from "./deleteAuditPolicy.generated";
import { InsufficientPermissionError } from "@tailor-platform/erp-kit/module";

const ctx = { actorId: "test-actor", permissions: ["audit:deleteAuditPolicy"] };

describe("deleteAuditPolicy", () => {
  it("deletes DRAFT policy", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(draftPolicy);

    const result = await run(db, { policyId: draftPolicy.id }, ctx);

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.policyId).toBe(draftPolicy.id);
    }
  });

  it("deletes associated PolicyFieldRules when deleting policy", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(draftPolicy);

    const result = await run(db, { policyId: draftPolicy.id }, ctx);

    expect(result.ok).toBe(true);
    // delete spy should be called twice: once for PolicyFieldRules, once for AuditPolicy
    expect(spies.delete).toHaveBeenCalledTimes(2);
  });

  it("does not affect previously recorded audit entries", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(draftPolicy);

    const result = await run(db, { policyId: draftPolicy.id }, ctx);

    expect(result.ok).toBe(true);
    // delete spy is called only for PolicyFieldRule and AuditPolicy, not AuditEntry
    expect(spies.delete).toHaveBeenCalledTimes(2);
  });

  it("rejects deletion of ACTIVE policy", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(activePolicy);

    const result = await run(db, { policyId: activePolicy.id }, ctx);

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(InvalidStateError);
    }
  });

  it("rejects deletion of INACTIVE policy", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(inactivePolicy);

    const result = await run(db, { policyId: inactivePolicy.id }, ctx);

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(InvalidStateError);
    }
  });

  it("rejects when policy does not exist", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(undefined);

    const result = await run(db, { policyId: "nonexistent" }, ctx);

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(PolicyNotFoundError);
    }
  });

  it("rejects when caller lacks manageAuditPolicies permission", async () => {
    const { db } = createMockDb<Transaction>();
    const denied = { actorId: "test-actor", permissions: [] as string[] };
    const cmd = deleteAuditPolicy();

    const result = await cmd(db, { policyId: draftPolicy.id }, denied);

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(InsufficientPermissionError);
    }
  });

  it("rejects when company-scoped caller deletes policy for a different company", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(draftPolicy); // policy with companyId: "company-1"
    const scopedCtx = { ...ctx, companyId: "company-2" };

    const result = await run(db, { policyId: draftPolicy.id }, scopedCtx);

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(UnauthorizedError);
    }
  });

  it("rejects when global-scoped caller deletes company-scoped policy", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(draftPolicy); // policy with companyId: "company-1"
    const globalCtx = { ...ctx, companyId: null };

    const result = await run(db, { policyId: draftPolicy.id }, globalCtx);

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(UnauthorizedError);
    }
  });
});
