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 { ForbiddenError } from "../lib/errors.generated";
import { baseAllowedPreference, baseOptOutPreference } from "../testing/fixtures";
import { run } from "./getNotificationPreference";

describe("getNotificationPreference", () => {
  const ctx: QueryContext = {
    actorId: "user-1",
    permissions: [],
  };

  it("returns the persisted NotificationPreference row when found by (userId, categoryId, channelId)", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    mock.enqueueResults([{ ...baseAllowedPreference }]);

    const result = await run(
      mock.db,
      { userId: "user-1", categoryId: "category-2", channelId: "channel-1" },
      ctx,
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.preference).not.toBeNull();
      expect(result.value.preference?.id).toBe(baseAllowedPreference.id);
    }
  });

  it("returns null when no row has been persisted for the triple", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    mock.enqueueResults([]);

    const result = await run(
      mock.db,
      { userId: "user-1", categoryId: "category-2", channelId: "channel-1" },
      ctx,
    );

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

  it("returns allowed = false rows when the user has explicitly opted out", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    mock.enqueueResults([{ ...baseOptOutPreference }]);

    const result = await run(
      mock.db,
      { userId: "user-1", categoryId: "category-2", channelId: "channel-1" },
      ctx,
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.preference?.allowed).toBe(false);
    }
  });

  it("rejects cross-user reads with FORBIDDEN", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();

    const result = await run(
      mock.db,
      { userId: "user-other", categoryId: "category-2", channelId: "channel-1" },
      ctx,
    );

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