import { type CommandContext, InsufficientPermissionError } from "@tailor-platform/erp-kit/core";
import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import {
  PolicyNotFoundError,
  InvalidStateError,
  IncompletePolicyError,
  ConflictingActivePolicyError,
  EntityTypeNotRegisteredError,
  UnauthorizedError,
} from "../lib/errors.generated";
import { draftPolicy, activePolicy, inactivePolicy, companyBoundEntity } from "../testing/fixtures";
import { run } from "./activateAuditPolicy";
import { activateAuditPolicy } from "./activateAuditPolicy.generated";

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

describe("activateAuditPolicy", () => {
  it("activates DRAFT policy to ACTIVE", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [draftPolicy],
      [companyBoundEntity],
      [],
      [{ ...draftPolicy, status: "ACTIVE" }],
    );

    const result = await mock.withTx((trx) => run(trx, { policyId: "policy-1" }, ctx));

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

  it("begins audit capture after activation", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [draftPolicy],
      [companyBoundEntity],
      [],
      [{ ...draftPolicy, status: "ACTIVE" }],
    );

    const result = await mock.withTx((trx) => run(trx, { policyId: "policy-1" }, 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 is the gate for logAuditEvent to capture events
    expect(mock.updates[0].updateValues()).toEqual(expect.objectContaining({ status: "ACTIVE" }));
    expect(mock.updates).toHaveLength(1);
  });

  it("rejects activation of ACTIVE policy", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([activePolicy]);

    const result = await mock.withTx((trx) => run(trx, { policyId: activePolicy.id }, ctx));

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

  it("rejects activation of INACTIVE policy", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([inactivePolicy]);

    const result = await mock.withTx((trx) => run(trx, { policyId: inactivePolicy.id }, ctx));

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

  it("rejects activation when conflicting ACTIVE policy exists", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([draftPolicy], [companyBoundEntity], [activePolicy]);

    const result = await mock.withTx((trx) => run(trx, { policyId: "policy-1" }, ctx));

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

  it("rejects activation when entity name is missing", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const policyNoEntity = { ...draftPolicy, entityName: "" };
    mock.enqueueResults([policyNoEntity]);

    const result = await mock.withTx((trx) => run(trx, { policyId: "policy-1" }, ctx));

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

  it("rejects activation when operation type is missing", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const policyNoOp = { ...draftPolicy, operationType: "" };
    mock.enqueueResults([policyNoOp]);

    const result = await mock.withTx((trx) => run(trx, { policyId: "policy-1" }, ctx));

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

  it("rejects when policy does not exist", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

    const result = await mock.withTx((trx) => run(trx, { 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 mock = createKyselyMock<Namespace["main-db"]>();
    const command = activateAuditPolicy();
    const noPermCtx: CommandContext = {
      actorId: "test-actor",
      permissions: [],
    };

    const result = await mock.withTx((trx) => command(trx, { policyId: "policy-1" }, noPermCtx));

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

  it("rejects when company-scoped caller activates policy for a different company", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([draftPolicy]); // policy with companyId: "company-1"
    const scopedCtx = { ...ctx, companyId: "company-2" };

    const result = await mock.withTx((trx) => run(trx, { policyId: "policy-1" }, scopedCtx));

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

  it("rejects when global-scoped caller activates company-scoped policy", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([draftPolicy]); // policy with companyId: "company-1"
    const globalCtx = { ...ctx, companyId: null };

    const result = await mock.withTx((trx) => run(trx, { policyId: "policy-1" }, globalCtx));

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

  it("rejects when target entity is no longer registered", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([draftPolicy], []); // policy lookup, entity not found

    const result = await mock.withTx((trx) => run(trx, { policyId: "policy-1" }, ctx));

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