import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  PolicyNotFoundError,
  InvalidStateError,
  ConflictingActivePolicyError,
  UnauthorizedError,
} from "../lib/errors.generated";
import { draftPolicy, activePolicy, inactivePolicy } from "../testing/fixtures";
import { run } from "./reactivateAuditPolicy";
import { reactivateAuditPolicy } from "./reactivateAuditPolicy.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:reactivateAuditPolicy"],
};

describe("reactivateAuditPolicy", () => {
  it("reactivates INACTIVE policy to ACTIVE", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(inactivePolicy); // policy lookup
    spies.select.mockReturnValueOnce(undefined); // no conflicting policy
    spies.update.mockReturnValue({ ...inactivePolicy, status: "ACTIVE" });

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

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

  it("resumes audit capture after reactivation", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(inactivePolicy);
    spies.select.mockReturnValueOnce(undefined);
    spies.update.mockReturnValue({ ...inactivePolicy, status: "ACTIVE" });

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

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

  it("rejects reactivation 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 reactivation 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 reactivation when conflicting ACTIVE policy exists", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(inactivePolicy); // policy lookup
    spies.select.mockReturnValueOnce(activePolicy); // conflicting policy

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

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

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

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

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

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

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

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

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

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

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