import { InsufficientPermissionError } from "@tailor-platform/erp-kit/core";
import type { QueryContext } 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 { UnauthorizedError } from "../lib/errors.generated";
import {
  activePolicy,
  draftPolicy,
  inactivePolicy,
  globalActivePolicy,
  globalDraftPolicy,
} from "../testing/fixtures";
import { run } from "./listAuditPolicies";

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

describe("listAuditPolicies", () => {
  it("returns all policies when no filters applied", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([activePolicy, draftPolicy, globalActivePolicy], []);

    const result = await run(mock.db, {}, ctx);

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.items).toHaveLength(3);
    }
  });

  it("returns policies filtered by entityName", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([activePolicy, draftPolicy], []);

    const result = await run(mock.db, { entityName: "SalesOrder" }, ctx);

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.items).toHaveLength(2);
      for (const item of result.value.items) {
        expect(item.policy.entityName).toBe("SalesOrder");
      }
    }
  });

  it("returns policies filtered by status", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([activePolicy, globalActivePolicy], []);

    const result = await run(mock.db, { status: "ACTIVE" }, ctx);

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.items).toHaveLength(2);
      for (const item of result.value.items) {
        expect(item.policy.status).toBe("ACTIVE");
      }
    }
  });

  it("returns policies filtered by companyId", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([activePolicy, draftPolicy, inactivePolicy], []);

    const result = await run(mock.db, { companyId: "company-1" }, ctx);

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.items).toHaveLength(3);
      for (const item of result.value.items) {
        expect(item.policy.companyId).toBe("company-1");
      }
    }
  });

  it("returns only global policies when companyId filter is explicitly null", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([globalActivePolicy, globalDraftPolicy], []);

    const result = await run(mock.db, { companyId: null }, ctx);

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.items).toHaveLength(2);
      for (const item of result.value.items) {
        expect(item.policy.companyId).toBeNull();
      }
    }
  });

  it("returns policies filtered by operationType", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([activePolicy], []);

    const result = await run(mock.db, { operationType: "UPDATE" }, ctx);

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.items).toHaveLength(1);
      expect(result.value.items[0].policy.operationType).toBe("UPDATE");
    }
  });

  it("combines multiple filter criteria", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([activePolicy], []);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.items).toHaveLength(1);
    }
  });

  it("returns policy objects with expected fields", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([activePolicy], []);

    const result = await run(mock.db, { status: "ACTIVE" }, ctx);

    expect(result.ok).toBe(true);
    if (result.ok) {
      const item = result.value.items[0];
      expect(item).toHaveProperty("policy");
      expect(item).toHaveProperty("fieldRules");
      expect(item.policy).toHaveProperty("id");
      expect(item.policy).toHaveProperty("entityName");
      expect(item.policy).toHaveProperty("companyId");
      expect(item.policy).toHaveProperty("operationType");
      expect(item.policy).toHaveProperty("status");
    }
  });

  it("returns empty list when no policies match", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

    const result = await run(mock.db, { entityName: "NonExistent" }, ctx);

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.items).toHaveLength(0);
      expect(result.value.hasNextPage).toBe(false);
    }
  });

  it("paginates results correctly", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const manyPolicies = Array.from({ length: 3 }, (_, i) => ({
      ...activePolicy,
      id: `policy-${i}`,
    }));
    mock.enqueueResults(manyPolicies, []);

    const result = await run(mock.db, { limit: 2 }, ctx);

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.items).toHaveLength(2);
      expect(result.value.hasNextPage).toBe(true);
    }
  });

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

    const result = await run(mock.db, {}, noPermsCtx);

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

  it("rejects when caller with company-scoped permission requests policies for a different company", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const scopedCtx: QueryContext = {
      actorId: "test-actor",
      permissions: ["audit:audit:manageAuditPolicies"],
      companyId: "company-1",
    };

    const result = await run(mock.db, { companyId: "company-2" }, scopedCtx);

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

  it("returns only global policies when caller has global-scoped permission", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([globalActivePolicy, globalDraftPolicy], []);
    const globalCtx: QueryContext = {
      actorId: "test-actor",
      permissions: ["audit:audit:manageAuditPolicies"],
      companyId: null,
    };

    const result = await run(mock.db, {}, globalCtx);

    expect(result.ok).toBe(true);
    if (result.ok) {
      for (const item of result.value.items) {
        expect(item.policy.companyId).toBeNull();
      }
    }
  });

  it("rejects when global-scoped caller requests company-scoped policies", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const globalCtx: QueryContext = {
      actorId: "test-actor",
      permissions: ["audit:audit:manageAuditPolicies"],
      companyId: null,
    };

    const result = await run(mock.db, { companyId: "company-1" }, globalCtx);

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