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 {
  EntityTypeNotRegisteredError,
  ScopeMismatchError,
  InvalidOperationTypeError,
  InvalidFieldNameError,
  DuplicateFieldNameError,
  InvalidSensitivityModeError,
  UnauthorizedError,
} from "../lib/errors.generated";
import {
  companyBoundEntity,
  globalEntity,
  draftPolicy,
  globalDraftPolicy,
} from "../testing/fixtures";
import { run } from "./createAuditPolicy";
import { createAuditPolicy } from "./createAuditPolicy.generated";

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

describe("createAuditPolicy", () => {
  it("creates policy in DRAFT status", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([companyBoundEntity], [{ ...draftPolicy, id: "new-policy-id" }]);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          entityName: "SalesOrder",
          companyId: "company-1",
          operationType: "UPDATE",
        },
        ctx,
      ),
    );

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

  it("creates policy with company scope for company-bound entity", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [companyBoundEntity],
      [{ ...draftPolicy, id: "new-policy-id", companyId: "company-1" }],
    );

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          entityName: "SalesOrder",
          companyId: "company-1",
          operationType: "CREATE",
        },
        ctx,
      ),
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.policy.companyId).toBe("company-1");
    }
  });

  it("creates policy with global scope for global entity", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([globalEntity], [{ ...globalDraftPolicy, id: "new-policy-id" }]);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          entityName: "User",
          operationType: "CREATE",
        },
        ctx,
      ),
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.policy.companyId).toBeNull();
    }
  });

  it("creates policy with field-level rules and sensitivity modes", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([companyBoundEntity], [{ ...draftPolicy, id: "new-policy-id" }]);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          entityName: "SalesOrder",
          companyId: "company-1",
          operationType: "UPDATE",
          fieldRules: [
            { fieldName: "amount", sensitivityMode: "CAPTURE" },
            { fieldName: "customerId", sensitivityMode: "MASK" },
          ],
        },
        ctx,
      ),
    );

    expect(result.ok).toBe(true);
    // Policy insert + 1 bulk field rule insert
    expect(mock.inserts).toHaveLength(2);
  });

  it("creates policy without field-level rules (audits all eligible fields)", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([companyBoundEntity], [{ ...draftPolicy, id: "new-policy-id" }]);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          entityName: "SalesOrder",
          companyId: "company-1",
          operationType: "UPDATE",
        },
        ctx,
      ),
    );

    expect(result.ok).toBe(true);
    // Only policy insert, no field rule inserts
    expect(mock.inserts).toHaveLength(1);
  });

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

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          entityName: "NonExistentEntity",
          operationType: "CREATE",
        },
        ctx,
      ),
    );

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

  it("rejects company-scoped policy for global entity", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([globalEntity]);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          entityName: "User",
          companyId: "company-1",
          operationType: "CREATE",
        },
        ctx,
      ),
    );

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

  it("rejects global policy for company-bound entity", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([companyBoundEntity]);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          entityName: "SalesOrder",
          operationType: "CREATE",
        },
        ctx,
      ),
    );

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

  it("rejects duplicate field names in field-level rules", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([companyBoundEntity]);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          entityName: "SalesOrder",
          companyId: "company-1",
          operationType: "UPDATE",
          fieldRules: [
            { fieldName: "amount", sensitivityMode: "CAPTURE" },
            { fieldName: "amount", sensitivityMode: "MASK" },
          ],
        },
        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([companyBoundEntity]);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          entityName: "SalesOrder",
          companyId: "company-1",
          operationType: "UPDATE",
          fieldRules: [{ fieldName: "nonExistentField" }],
        },
        ctx,
      ),
    );

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

  it("rejects invalid sensitivity mode", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([companyBoundEntity]);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          entityName: "SalesOrder",
          companyId: "company-1",
          operationType: "UPDATE",
          fieldRules: [{ fieldName: "amount", sensitivityMode: "INVALID_MODE" }],
        },
        ctx,
      ),
    );

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

  it("rejects invalid operation type", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([companyBoundEntity]);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          entityName: "SalesOrder",
          companyId: "company-1",
          operationType: "INVALID_OP",
        },
        ctx,
      ),
    );

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

  it("rejects empty field name in field-level rules", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([companyBoundEntity]);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          entityName: "SalesOrder",
          companyId: "company-1",
          operationType: "UPDATE",
          fieldRules: [{ fieldName: "" }],
        },
        ctx,
      ),
    );

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

  it("defaults sensitivityMode to CAPTURE when not specified", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([companyBoundEntity], [{ ...draftPolicy, id: "new-policy-id" }]);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          entityName: "SalesOrder",
          companyId: "company-1",
          operationType: "UPDATE",
          fieldRules: [{ fieldName: "amount" }],
        },
        ctx,
      ),
    );

    expect(result.ok).toBe(true);
    // Verify the field rule insert was called with sensitivityMode defaulting to CAPTURE
    expect(mock.inserts[1].insertRows()).toEqual(
      expect.arrayContaining([
        expect.objectContaining({
          fieldName: "amount",
          sensitivityMode: "CAPTURE",
        }),
      ]),
    );
  });

  it("rejects when caller lacks manageAuditPolicies permission", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const command = createAuditPolicy();
    const noPermCtx: CommandContext = { actorId: "test-actor", permissions: [] };

    const result = await mock.withTx((trx) =>
      command(
        trx,
        {
          entityName: "SalesOrder",
          companyId: "company-1",
          operationType: "UPDATE",
        },
        noPermCtx,
      ),
    );

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

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

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          entityName: "SalesOrder",
          companyId: "company-1",
          operationType: "CREATE",
        },
        scopedCtx,
      ),
    );

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

  it("creates policy with global scope when companyId is explicitly null", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([globalEntity], [{ ...globalDraftPolicy, id: "new-policy-id" }]);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          entityName: "User",
          companyId: null,
          operationType: "CREATE",
        },
        ctx,
      ),
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.policy.companyId).toBeNull();
    }
  });

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

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          entityName: "SalesOrder",
          companyId: "company-1",
          operationType: "CREATE",
        },
        globalCtx,
      ),
    );

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