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

describe("reactivateUser", () => {
  // Error cases
  it("throws when user does not exist", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

    const result = await mock.withTx((trx) => run(trx, { userId: "nonexistent-user" }));
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(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 ACTIVE", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([activeUser]);

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

  // Success cases
  it("reactivates INACTIVE user to ACTIVE", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const reactivatedUser = {
      ...inactiveUser,
      status: "ACTIVE" as const,
      updatedAt: new Date("2024-01-15T00:00:00.000Z"),
    };
    // Permissions are recomputed from the preserved role assignments
    const finalUser = { ...reactivatedUser, permissions: ["orders:read"] };

    mock.enqueueResults(
      [inactiveUser], // transition: load user
      [reactivatedUser], // transition: update status
      [{ permissions: ["orders:read"] }], // recompute: roles query
      [finalUser], // recompute: update permissions
    );

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.user.status).toBe("ACTIVE");
      expect(result.value.user.updatedAt).not.toBeNull();
    }
    // The recompute restores permissions from the preserved role assignments
    expect(mock.updates.at(-1)?.updateValues()).toEqual({ permissions: ["orders:read"] });
  });
});
