import { 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,
  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";

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

describe("updateAuditPolicy", () => {
  it("updates operation type on DRAFT policy", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([draftPolicy], [{ ...draftPolicy, operationType: "DELETE" }]);

    const result = await mock.withTx((trx) =>
      run(trx, { 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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [draftPolicy],
      [companyBoundEntity],
      [], // delete PolicyFieldRule
      [{ id: "rule-new", fieldName: "amount", sensitivityMode: "CAPTURE" }],
    );

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

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

  it("updates sensitivity modes on field-level rules", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [draftPolicy],
      [companyBoundEntity],
      [],
      [{ id: "rule-new", fieldName: "amount", sensitivityMode: "MASK" }],
    );

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([draftPolicy], [companyBoundEntity], [], [{ id: "rule-new" }]);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([draftPolicy], [companyBoundEntity], []);

    const result = await mock.withTx((trx) =>
      run(trx, { 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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([draftPolicy], [companyBoundEntity], [], [{ id: "rule-new" }]);

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

    expect(result.ok).toBe(true);
    expect(mock.inserts[0].insertRows()).toEqual(
      expect.arrayContaining([expect.objectContaining({ sensitivityMode: "CAPTURE" })]),
    );
  });

  it("defaults sensitivityMode to CAPTURE when modifying a field-level rule and sensitivityMode is omitted", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([draftPolicy], [companyBoundEntity], [], [{ id: "rule-new" }]);

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

    expect(result.ok).toBe(true);
    expect(mock.inserts[0].insertRows()).toEqual(
      expect.arrayContaining([expect.objectContaining({ sensitivityMode: "CAPTURE" })]),
    );
  });

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

    const result = await mock.withTx((trx) =>
      run(trx, { 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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([inactivePolicy]);

    const result = await mock.withTx((trx) =>
      run(trx, { 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 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 duplicate field names", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([draftPolicy], [companyBoundEntity]);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([draftPolicy], [companyBoundEntity]);

    const result = await mock.withTx((trx) =>
      run(trx, { 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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([draftPolicy]);

    const result = await mock.withTx((trx) =>
      run(trx, { 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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([draftPolicy], [companyBoundEntity]);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          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 mock = createKyselyMock<Namespace["main-db"]>();
    const denied = { actorId: "test-actor", permissions: [] as string[] };
    const cmd = updateAuditPolicy();

    const result = await mock.withTx((trx) => cmd(trx, { 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 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: 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 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: draftPolicy.id }, globalCtx));

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