import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { DB } from "../generated/kysely-tailordb";
import { UnauthorizedError } from "../lib/errors.generated";
import {
  activePolicy,
  draftPolicy,
  inactivePolicy,
  globalActivePolicy,
  globalDraftPolicy,
} from "../testing/fixtures";
import { run } from "./listAuditPolicies";
import { InsufficientPermissionError } from "@tailor-platform/erp-kit/module";
import type { QueryContext } from "@tailor-platform/erp-kit/module";

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

describe("listAuditPolicies", () => {
  it("returns all policies when no filters applied", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue([activePolicy, draftPolicy, globalActivePolicy]);

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

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

  it("returns policies filtered by entityName", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue([activePolicy, draftPolicy]);

    const result = await run(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 { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue([activePolicy, globalActivePolicy]);

    const result = await run(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 { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue([activePolicy, draftPolicy, inactivePolicy]);

    const result = await run(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 { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue([globalActivePolicy, globalDraftPolicy]);

    const result = await run(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 { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue([activePolicy]);

    const result = await run(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 { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue([activePolicy]);

    const result = await run(
      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 { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue([activePolicy]);

    const result = await run(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 { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue([]);

    const result = await run(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 { db, spies } = createMockDb<DB>();
    const manyPolicies = Array.from({ length: 3 }, (_, i) => ({
      ...activePolicy,
      id: `policy-${i}`,
    }));
    spies.select.mockReturnValue(manyPolicies);

    const result = await run(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 { db } = createMockDb<DB>();
    const noPermsCtx: QueryContext = { actorId: "test-actor", permissions: [] };

    const result = await run(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 { db } = createMockDb<DB>();
    const scopedCtx: QueryContext = {
      actorId: "test-actor",
      permissions: ["audit:manageAuditPolicies"],
      companyId: "company-1",
    };

    const result = await run(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 { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue([globalActivePolicy, globalDraftPolicy]);
    const globalCtx: QueryContext = {
      actorId: "test-actor",
      permissions: ["audit:manageAuditPolicies"],
      companyId: null,
    };

    const result = await run(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 { db } = createMockDb<DB>();
    const globalCtx: QueryContext = {
      actorId: "test-actor",
      permissions: ["audit:manageAuditPolicies"],
      companyId: null,
    };

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

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