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,
  baseInAppChannel,
  baseOptionalCategory,
  baseOptOutPreference,
  baseTransactionalCategory,
} from "../testing/fixtures";
import { run } from "./updateNotificationPreference";

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

  it("inserts a NotificationPreference row with allowed=false for an optional category × channel pair", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    // 1. load category, 2. load channel, 3. existing preference (none), 4. insert preference
    mock.enqueueResults(
      [{ ...baseOptionalCategory }],
      [{ ...baseInAppChannel }],
      [],
      [{ ...baseOptOutPreference }],
    );

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.preference.allowed).toBe(false);
    }
    expect(mock.inserts.length).toBeGreaterThan(0);
  });

  it("updates an existing NotificationPreference row's allowed flag", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    // 1. load category, 2. load channel, 3. existing preference (found), 4. update preference
    mock.enqueueResults(
      [{ ...baseOptionalCategory }],
      [{ ...baseInAppChannel }],
      [{ ...baseAllowedPreference }],
      [{ ...baseAllowedPreference, allowed: false }],
    );

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.preference.allowed).toBe(false);
    }
    expect(mock.updates.length).toBeGreaterThan(0);
    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",
          categoryId: "category-2",
          channelId: "channel-1",
          allowed: false,
        },
        ctx,
      ),
    );

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

  it("returns CATEGORY_NOT_OPT_OUT_ABLE when toggling allowed=false on a transactional category", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    mock.enqueueResults([{ ...baseTransactionalCategory }], [{ ...baseInAppChannel }]);

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

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

  it("returns CATEGORY_NOT_FOUND when categoryId does not match", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    mock.enqueueResults([]);

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

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

  it("returns CHANNEL_NOT_FOUND when channelId does not match", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    mock.enqueueResults([{ ...baseOptionalCategory }], []);

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

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

  it("returns MISSING_REQUIRED_FIELD when allowed is not a boolean", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          userId: "user-1",
          categoryId: "category-2",
          channelId: "channel-1",
        } as unknown as Parameters<typeof run>[1],
        ctx,
      ),
    );

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

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

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

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(MissingRequiredFieldError);
    }
    // Blank key must not reach the category lookup.
    expect(mock.selects.length).toBe(0);
  });

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

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

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

  it("submitting the same allowed value twice produces a single row in the final state (idempotent)", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    // First call: no row → insert.
    // Second call: row found → update converges on same state.
    mock.enqueueResults(
      [{ ...baseOptionalCategory }],
      [{ ...baseInAppChannel }],
      [],
      [{ ...baseOptOutPreference }],
      [{ ...baseOptionalCategory }],
      [{ ...baseInAppChannel }],
      [{ ...baseOptOutPreference }],
      [{ ...baseOptOutPreference }],
    );

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

    expect(r1.ok).toBe(true);
    expect(r2.ok).toBe(true);
    if (r1.ok && r2.ok) {
      expect(r1.value.preference.allowed).toBe(false);
      expect(r2.value.preference.allowed).toBe(false);
    }
    expect(mock.inserts.length).toBe(1);
  });
});
