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 "./deactivateAuditPolicy";
import { deactivateAuditPolicy } from "./deactivateAuditPolicy.generated";
import { InsufficientPermissionError } from "@tailor-platform/erp-kit/module";
import type { CommandContext } from "@tailor-platform/erp-kit/module";

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

describe("deactivateAuditPolicy", () => {
  it("deactivates ACTIVE policy to INACTIVE", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(activePolicy); // policy lookup
    spies.update.mockReturnValue({ ...activePolicy, status: "INACTIVE" });

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.policy.status).toBe("INACTIVE");
    }
  });

  it("stops new audit capture after deactivation", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(activePolicy);
    spies.update.mockReturnValue({ ...activePolicy, status: "INACTIVE" });

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.policy.status).toBe("INACTIVE");
    }
    // Verify that the DB update sets status to INACTIVE, which is the gate that stops logAuditEvent capture
    expect(spies.set).toHaveBeenCalledWith(expect.objectContaining({ status: "INACTIVE" }));
    expect(spies.update).toHaveBeenCalledTimes(1);
  });

  it("does not delete previously recorded audit entries", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(activePolicy);
    spies.update.mockReturnValue({ ...activePolicy, status: "INACTIVE" });

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.policy.status).toBe("INACTIVE");
    }
    // Verify no delete operations are issued — previously recorded audit entries are preserved
    expect(spies.delete).not.toHaveBeenCalled();
  });

  it("rejects deactivation of 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(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(InvalidStateError);
    }
  });

  it("rejects deactivation 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 command = deactivateAuditPolicy();
    const noPermCtx: CommandContext = {
      actorId: "test-actor",
      permissions: [],
    };

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

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

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

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

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

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

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

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