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 {
  CategoryNotFoundError,
  ChannelNotFoundError,
  ForbiddenError,
} from "../lib/errors.generated";
import {
  baseAllowedPreference,
  baseEventCategoryBinding,
  baseInAppChannel,
  baseOptOutPreference,
  baseOptionalCategory,
  baseOptionalEventBinding,
  baseTransactionalCategory,
} from "../testing/fixtures";
import { run } from "./getEffectiveNotificationPreference";

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

  it("returns { allowed: true, source: 'TRANSACTIONAL_OVERRIDE' } when the event's binding is transactional", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    mock.enqueueResults([{ ...baseEventCategoryBinding }], [{ ...baseTransactionalCategory }]);

    const result = await run(
      mock.db,
      { userId: "user-1", eventType: "PO_ISSUED", channelKey: "IN_APP" },
      ctx,
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.effective.allowed).toBe(true);
      expect(result.value.effective.source).toBe("TRANSACTIONAL_OVERRIDE");
    }
  });

  it("returns { allowed: true, source: 'TRANSACTIONAL_OVERRIDE' } when the category is not opt-out-able even if the binding is not transactional", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    mock.enqueueResults(
      [{ ...baseOptionalEventBinding, categoryId: "category-1" }],
      [{ ...baseTransactionalCategory }],
    );

    const result = await run(
      mock.db,
      { userId: "user-1", eventType: "ANNOUNCEMENT_PUBLISHED", channelKey: "IN_APP" },
      ctx,
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.effective.source).toBe("TRANSACTIONAL_OVERRIDE");
    }
  });

  it("returns { allowed: false, source: 'USER_PREFERENCE' } when the user has an explicit allowed = false row", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    mock.enqueueResults(
      [{ ...baseOptionalEventBinding }],
      [{ ...baseOptionalCategory }],
      [{ ...baseInAppChannel }],
      [{ ...baseOptOutPreference }],
    );

    const result = await run(
      mock.db,
      { userId: "user-1", eventType: "ANNOUNCEMENT_PUBLISHED", channelKey: "IN_APP" },
      ctx,
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.effective.allowed).toBe(false);
      expect(result.value.effective.source).toBe("USER_PREFERENCE");
    }
  });

  it("returns { allowed: true, source: 'USER_PREFERENCE' } when the user has an explicit allowed = true row", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    mock.enqueueResults(
      [{ ...baseOptionalEventBinding }],
      [{ ...baseOptionalCategory }],
      [{ ...baseInAppChannel }],
      [{ ...baseAllowedPreference }],
    );

    const result = await run(
      mock.db,
      { userId: "user-1", eventType: "ANNOUNCEMENT_PUBLISHED", channelKey: "IN_APP" },
      ctx,
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.effective.allowed).toBe(true);
      expect(result.value.effective.source).toBe("USER_PREFERENCE");
    }
  });

  it("returns { allowed: true, source: 'DEFAULT' } when no preference row exists for the triple", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    mock.enqueueResults(
      [{ ...baseOptionalEventBinding }],
      [{ ...baseOptionalCategory }],
      [{ ...baseInAppChannel }],
      [],
    );

    const result = await run(
      mock.db,
      { userId: "user-1", eventType: "ANNOUNCEMENT_PUBLISHED", channelKey: "IN_APP" },
      ctx,
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.effective.allowed).toBe(true);
      expect(result.value.effective.source).toBe("DEFAULT");
    }
  });

  it("rejects a caller requesting another user's preference with FORBIDDEN", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();

    const result = await run(
      mock.db,
      { userId: "user-other", eventType: "ANNOUNCEMENT_PUBLISHED", channelKey: "IN_APP" },
      ctx,
    );

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

  it("returns CATEGORY_NOT_FOUND when no EventCategoryBinding matches the supplied eventType", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    mock.enqueueResults([]);

    const result = await run(
      mock.db,
      { userId: "user-1", eventType: "missing", channelKey: "IN_APP" },
      ctx,
    );

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

  it("returns CHANNEL_NOT_FOUND when the channelKey resolves to no NotificationChannel row", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    mock.enqueueResults([{ ...baseOptionalEventBinding }], [{ ...baseOptionalCategory }], []);

    const result = await run(
      mock.db,
      { userId: "user-1", eventType: "ANNOUNCEMENT_PUBLISHED", channelKey: "IN_APP" },
      ctx,
    );

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