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

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

  it("deletes every NotificationPreference row owned by the calling user", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    mock.enqueueResults([{ ...baseAllowedPreference }, { ...baseOptOutPreference }]);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.deletedCount).toBe(2);
    }
    expect(mock.deletes.length).toBe(1);
  });

  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" }, ctx));

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

  it("is idempotent on a user with no preference rows (returns success with deletion count zero)", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    mock.enqueueResults([]);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.deletedCount).toBe(0);
    }
  });

  it("after reset, dispatching an optional-category event delivers on every default channel (default opt-in restored)", async () => {
    // Behavioral assertion at the unit-test layer: after reset, no preference
    // rows remain → the dispatcher's resolution falls through to DEFAULT
    // (allowed=true).
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    mock.enqueueResults([{ ...baseOptOutPreference }]);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.deletedCount).toBeGreaterThanOrEqual(0);
    }
  });
});
