import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import { testNotFound } from "../../../testing";
import type { Namespace } from "../generated/kysely-tailordb";
import { InvalidStatusTransitionError, UserNotFoundError } from "../lib/errors.generated";
import { activeUser, inactiveUser, pendingUser } from "../testing/fixtures";
import { run } from "./deactivateUser";

describe("deactivateUser", () => {
  it(
    "throws when user does not exist",
    testNotFound(run, { userId: "nonexistent-user" }, UserNotFoundError),
  );

  it("throws when user is PENDING", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([pendingUser]);

    const result = await mock.withTx((trx) => run(trx, { userId: pendingUser.id }));
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(InvalidStatusTransitionError);
    }
  });

  it("throws when user is already INACTIVE", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([inactiveUser]);

    const result = await mock.withTx((trx) => run(trx, { userId: inactiveUser.id }));
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(InvalidStatusTransitionError);
    }
  });

  // Success cases
  it("deactivates ACTIVE user to INACTIVE", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const deactivatedUser = {
      ...activeUser,
      status: "INACTIVE" as const,
      updatedAt: new Date("2024-01-15T00:00:00.000Z"),
    };
    // Deactivation clears permissions; role assignments are preserved
    const finalUser = { ...deactivatedUser, permissions: [] };

    mock.enqueueResults(
      [activeUser], // transition: load user
      [deactivatedUser], // transition: update status
      [], // recompute: no rows because user is INACTIVE
      [finalUser], // recompute: update permissions
    );

    const result = await mock.withTx((trx) =>
      run(trx, {
        userId: activeUser.id,
      }),
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.user.status).toBe("INACTIVE");
      expect(result.value.user.updatedAt).not.toBeNull();
    }
    // The recompute clears permissions to []
    expect(mock.updates.at(-1)?.updateValues()).toEqual({ permissions: [] });
  });
});
