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

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

describe("updateAuditPolicy", () => {
  it("updates operation type on DRAFT policy", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(draftPolicy);
    spies.update.mockReturnValueOnce({ ...draftPolicy, operationType: "DELETE" });

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.policy.operationType).toBe("DELETE");
    }
  });

  it("updates field-level rules on DRAFT policy", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(draftPolicy);
    spies.select.mockReturnValueOnce(companyBoundEntity);
    spies.update.mockReturnValueOnce(draftPolicy);
    spies.insert.mockReturnValue({
      id: "rule-new",
      fieldName: "amount",
      sensitivityMode: "CAPTURE",
    });

    const result = await run(
      db,
      { policyId: draftPolicy.id, fieldRules: [{ fieldName: "amount" }] },
      ctx,
    );

    expect(result.ok).toBe(true);
  });

  it("updates sensitivity modes on field-level rules", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(draftPolicy);
    spies.select.mockReturnValueOnce(companyBoundEntity);
    spies.update.mockReturnValueOnce(draftPolicy);
    spies.insert.mockReturnValue({ id: "rule-new", fieldName: "amount", sensitivityMode: "MASK" });

    const result = await run(
      db,
      { policyId: draftPolicy.id, fieldRules: [{ fieldName: "amount", sensitivityMode: "MASK" }] },
      ctx,
    );

    expect(result.ok).toBe(true);
  });

  it("adds new field-level rules to DRAFT policy", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(draftPolicy);
    spies.select.mockReturnValueOnce(companyBoundEntity);
    spies.update.mockReturnValueOnce(draftPolicy);
    spies.insert.mockReturnValue({ id: "rule-new" });

    const result = await run(
      db,
      {
        policyId: draftPolicy.id,
        fieldRules: [
          { fieldName: "amount", sensitivityMode: "CAPTURE" },
          { fieldName: "status", sensitivityMode: "HASH" },
        ],
      },
      ctx,
    );

    expect(result.ok).toBe(true);
  });

  it("removes field-level rules from DRAFT policy", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(draftPolicy);
    spies.select.mockReturnValueOnce(companyBoundEntity);
    spies.update.mockReturnValueOnce(draftPolicy);

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

    expect(result.ok).toBe(true);
  });

  it("defaults sensitivityMode to CAPTURE when adding a field-level rule without explicit sensitivityMode", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(draftPolicy);
    spies.select.mockReturnValueOnce(companyBoundEntity);
    spies.update.mockReturnValueOnce(draftPolicy);
    spies.insert.mockReturnValue({ id: "rule-new" });

    const result = await run(
      db,
      { policyId: draftPolicy.id, fieldRules: [{ fieldName: "amount" }] },
      ctx,
    );

    expect(result.ok).toBe(true);
    expect(spies.values).toHaveBeenCalledWith(
      expect.objectContaining({ sensitivityMode: "CAPTURE" }),
    );
  });

  it("defaults sensitivityMode to CAPTURE when modifying a field-level rule and sensitivityMode is omitted", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(draftPolicy);
    spies.select.mockReturnValueOnce(companyBoundEntity);
    spies.update.mockReturnValueOnce(draftPolicy);
    spies.insert.mockReturnValue({ id: "rule-new" });

    const result = await run(
      db,
      { policyId: draftPolicy.id, fieldRules: [{ fieldName: "status" }] },
      ctx,
    );

    expect(result.ok).toBe(true);
    expect(spies.values).toHaveBeenCalledWith(
      expect.objectContaining({ sensitivityMode: "CAPTURE" }),
    );
  });

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

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

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

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

    const result = await run(db, { policyId: inactivePolicy.id, operationType: "DELETE" }, 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 duplicate field names", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(draftPolicy);
    spies.select.mockReturnValueOnce(companyBoundEntity);

    const result = await run(
      db,
      {
        policyId: draftPolicy.id,
        fieldRules: [{ fieldName: "amount" }, { fieldName: "amount" }],
      },
      ctx,
    );

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

  it("rejects field names not in entity's auditableFields", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(draftPolicy);
    spies.select.mockReturnValueOnce(companyBoundEntity);

    const result = await run(
      db,
      { policyId: draftPolicy.id, fieldRules: [{ fieldName: "nonExistentField" }] },
      ctx,
    );

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

  it("rejects invalid operation type", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(draftPolicy);

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

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

  it("rejects invalid sensitivity mode", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(draftPolicy);
    spies.select.mockReturnValueOnce(companyBoundEntity);

    const result = await run(
      db,
      {
        policyId: draftPolicy.id,
        fieldRules: [{ fieldName: "amount", sensitivityMode: "INVALID" }],
      },
      ctx,
    );

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

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

    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 updates 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 updates 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);
    }
  });
});
