import { describe, expect, it } from "vitest";
import { createMockDb, testPermissionDenied } from "../../../testing/index";
import type { Transaction } 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";
import type { CommandContext } from "@tailor-platform/erp-kit/module";

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

describe("createAuditPolicy", () => {
  it("creates policy in DRAFT status", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(companyBoundEntity);
    spies.insert.mockReturnValue({ ...draftPolicy, id: "new-policy-id" });

    const result = await run(
      db,
      {
        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 { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(companyBoundEntity);
    spies.insert.mockReturnValue({ ...draftPolicy, id: "new-policy-id", companyId: "company-1" });

    const result = await run(
      db,
      {
        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 { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(globalEntity);
    spies.insert.mockReturnValue({ ...globalDraftPolicy, id: "new-policy-id" });

    const result = await run(
      db,
      {
        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 { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(companyBoundEntity);
    spies.insert.mockReturnValue({ ...draftPolicy, id: "new-policy-id" });

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

    expect(result.ok).toBe(true);
    // Policy insert + 2 field rule inserts
    expect(spies.insert).toHaveBeenCalledTimes(3);
  });

  it("creates policy without field-level rules (audits all eligible fields)", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(companyBoundEntity);
    spies.insert.mockReturnValue({ ...draftPolicy, id: "new-policy-id" });

    const result = await run(
      db,
      {
        entityName: "SalesOrder",
        companyId: "company-1",
        operationType: "UPDATE",
      },
      ctx,
    );

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

  it("rejects when entityName is not registered", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(undefined);

    const result = await run(
      db,
      {
        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 { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(globalEntity);

    const result = await run(
      db,
      {
        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 { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(companyBoundEntity);

    const result = await run(
      db,
      {
        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 { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(companyBoundEntity);

    const result = await run(
      db,
      {
        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 { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(companyBoundEntity);

    const result = await run(
      db,
      {
        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 { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(companyBoundEntity);

    const result = await run(
      db,
      {
        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 { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(companyBoundEntity);

    const result = await run(
      db,
      {
        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 { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(companyBoundEntity);

    const result = await run(
      db,
      {
        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 { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(companyBoundEntity);
    spies.insert.mockReturnValue({ ...draftPolicy, id: "new-policy-id" });

    const result = await run(
      db,
      {
        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(spies.values).toHaveBeenCalledWith(
      expect.objectContaining({
        fieldName: "amount",
        sensitivityMode: "CAPTURE",
      }),
    );
  });

  it(
    "rejects when caller lacks manageAuditPolicies permission",
    testPermissionDenied(createAuditPolicy(), {
      entityName: "SalesOrder",
      companyId: "company-1",
      operationType: "UPDATE",
    }),
  );

  it("rejects when company-scoped caller creates policy for a different company", async () => {
    const { db } = createMockDb<Transaction>();
    const scopedCtx = { ...ctx, companyId: "company-2" };

    const result = await run(
      db,
      {
        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 { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(globalEntity);
    spies.insert.mockReturnValue({ ...globalDraftPolicy, id: "new-policy-id" });

    const result = await run(
      db,
      {
        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 { db } = createMockDb<Transaction>();
    const globalCtx = { ...ctx, companyId: null };

    const result = await run(
      db,
      {
        entityName: "SalesOrder",
        companyId: "company-1",
        operationType: "CREATE",
      },
      globalCtx,
    );

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