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 {
  draftPolicy,
  activePolicy,
  inactivePolicy,
  globalActivePolicy,
  captureFieldRule,
  maskFieldRule,
} from "../testing/fixtures";
import { run } from "./getAuditPolicy";
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("getAuditPolicy", () => {
  it("returns audit policy when found by id", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(activePolicy);
    spies.select.mockReturnValueOnce([captureFieldRule, maskFieldRule]);

    const result = await run(db, { id: activePolicy.id }, ctx);

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.policy).toEqual(activePolicy);
    }
  });

  it("returns null when audit policy not found", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(undefined);

    const result = await run(db, { id: "nonexistent" }, ctx);

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.policy).toBeNull();
      expect(result.value.fieldRules).toEqual([]);
    }
  });

  it("returns DRAFT policy", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(draftPolicy);
    spies.select.mockReturnValueOnce([]);

    const result = await run(db, { id: draftPolicy.id }, ctx);

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

  it("returns ACTIVE policy", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(activePolicy);
    spies.select.mockReturnValueOnce([captureFieldRule]);

    const result = await run(db, { id: activePolicy.id }, ctx);

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.policy).toEqual(activePolicy);
      expect(result.value.policy!.status).toBe("ACTIVE");
    }
  });

  it("returns INACTIVE policy", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(inactivePolicy);
    spies.select.mockReturnValueOnce([]);

    const result = await run(db, { id: inactivePolicy.id }, ctx);

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.policy).toEqual(inactivePolicy);
      expect(result.value.policy!.status).toBe("INACTIVE");
    }
  });

  it("includes associated PolicyFieldRules in response", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(activePolicy);
    spies.select.mockReturnValueOnce([captureFieldRule, maskFieldRule]);

    const result = await run(db, { id: activePolicy.id }, ctx);

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.fieldRules).toEqual([captureFieldRule, maskFieldRule]);
      expect(result.value.fieldRules).toHaveLength(2);
    }
  });

  it("returns global policy when caller has global-scoped permission", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(globalActivePolicy);
    spies.select.mockReturnValueOnce([]);
    const globalScopedCtx: QueryContext = {
      actorId: "test-actor",
      permissions: ["audit:manageAuditPolicies"],
      companyId: null,
    };

    const result = await run(db, { id: globalActivePolicy.id }, globalScopedCtx);

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

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

    const result = await run(db, { id: activePolicy.id }, noPermsCtx);

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

  it("rejects when caller lacks permission for policy's company scope", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(activePolicy); // companyId: "company-1"
    const scopedCtx: QueryContext = {
      actorId: "test-actor",
      permissions: ["audit:manageAuditPolicies"],
      companyId: "company-2",
    };

    const result = await run(db, { id: activePolicy.id }, scopedCtx);

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

  it("rejects when global-scoped caller retrieves company-scoped policy", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(activePolicy); // companyId: "company-1"
    const globalCtx: QueryContext = {
      actorId: "test-actor",
      permissions: ["audit:manageAuditPolicies"],
      companyId: null,
    };

    const result = await run(db, { id: activePolicy.id }, globalCtx);

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