import type { CommandContext } 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,
  CategoryNotOptOutAbleError,
  ChannelNotFoundError,
  ForbiddenError,
  MissingRequiredFieldError,
} from "../lib/errors.generated";
import {
  baseAllowedPreference,
  baseEmailChannel,
  baseInAppChannel,
  baseOptionalCategory,
  baseOptOutPreference,
  baseTransactionalCategory,
} from "../testing/fixtures";
import { run } from "./bulkUpdateNotificationPreferences";

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

  it("atomically upserts every NotificationPreference row supplied in entries when all entries are valid", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    // Pre-flight: batch query returns all unique categories and channels.
    mock.enqueueResults(
      [{ ...baseOptionalCategory }],
      [{ ...baseInAppChannel }, { ...baseEmailChannel }],
      // Per-entry select-for-update probe (no existing row), then insert.
      [],
      [{ ...baseOptOutPreference }],
      [],
      [
        {
          ...baseAllowedPreference,
          id: "preference-x",
          channelId: "channel-2",
        },
      ],
    );

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          userId: "user-1",
          entries: [
            { categoryId: "category-2", channelId: "channel-1", allowed: false },
            { categoryId: "category-2", channelId: "channel-2", allowed: true },
          ],
        },
        ctx,
      ),
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.preferences).toHaveLength(2);
    }
    expect(mock.inserts.length).toBe(2);
  });

  it("rolls back the entire batch when one entry targets a transactional category with allowed=false", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    // Pre-flight: batch query returns both categories and channels in a single call each.
    mock.enqueueResults(
      [{ ...baseOptionalCategory }, { ...baseTransactionalCategory }],
      [{ ...baseInAppChannel }],
    );

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          userId: "user-1",
          entries: [
            { categoryId: "category-2", channelId: "channel-1", allowed: false },
            { categoryId: "category-1", channelId: "channel-1", allowed: false },
          ],
        },
        ctx,
      ),
    );

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(CategoryNotOptOutAbleError);
    }
    expect(mock.inserts.length).toBe(0);
    expect(mock.updates.length).toBe(0);
  });

  it("rolls back the entire batch when one entry references a non-existent category", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    mock.enqueueResults([]);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          userId: "user-1",
          entries: [{ categoryId: "missing", channelId: "channel-1", allowed: false }],
        },
        ctx,
      ),
    );

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

  it("rolls back the entire batch when one entry references a non-existent channel", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    // Category resolves; the channel lookup returns no row → CHANNEL_NOT_FOUND.
    mock.enqueueResults([{ ...baseOptionalCategory }], []);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          userId: "user-1",
          entries: [{ categoryId: "category-2", channelId: "missing", allowed: false }],
        },
        ctx,
      ),
    );

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

  it("returns FORBIDDEN when the caller's userId does not equal the target userId", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          userId: "user-other",
          entries: [{ categoryId: "category-2", channelId: "channel-1", allowed: false }],
        },
        ctx,
      ),
    );

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

  it("returns MISSING_REQUIRED_FIELD when entries is empty", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();

    const result = await mock.withTx((trx) => run(trx, { userId: "user-1", entries: [] }, ctx));

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

  it("supports mixing inserts and updates in the same call", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    // Pre-flight: batch query returns category and channels.
    mock.enqueueResults(
      [{ ...baseOptionalCategory }],
      [{ ...baseInAppChannel }, { ...baseEmailChannel }],
      // Entry-1: existing preference found, will be updated
      [{ ...baseAllowedPreference }],
      [{ ...baseAllowedPreference, allowed: false }],
      // Entry-2: no existing preference, will be inserted
      [],
      [
        {
          ...baseAllowedPreference,
          id: "preference-new",
          channelId: "channel-2",
        },
      ],
    );

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          userId: "user-1",
          entries: [
            { categoryId: "category-2", channelId: "channel-1", allowed: false },
            { categoryId: "category-2", channelId: "channel-2", allowed: true },
          ],
        },
        ctx,
      ),
    );

    expect(result.ok).toBe(true);
    expect(mock.updates.length).toBe(1);
    expect(mock.inserts.length).toBe(1);
  });

  it("submitting the same matrix twice converges on the same end state", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    // First call: category and channel queries, then insert
    mock.enqueueResults(
      [{ ...baseOptionalCategory }],
      [{ ...baseInAppChannel }],
      [],
      [{ ...baseOptOutPreference }],
      // Second call: same queries, but existing preference found so it's returned as-is
      [{ ...baseOptionalCategory }],
      [{ ...baseInAppChannel }],
      [{ ...baseOptOutPreference }],
      [{ ...baseOptOutPreference }],
    );

    const r1 = await mock.withTx((trx) =>
      run(
        trx,
        {
          userId: "user-1",
          entries: [{ categoryId: "category-2", channelId: "channel-1", allowed: false }],
        },
        ctx,
      ),
    );
    const r2 = await mock.withTx((trx) =>
      run(
        trx,
        {
          userId: "user-1",
          entries: [{ categoryId: "category-2", channelId: "channel-1", allowed: false }],
        },
        ctx,
      ),
    );

    expect(r1.ok).toBe(true);
    expect(r2.ok).toBe(true);
    expect(mock.inserts.length).toBe(1);
  });
});
