import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import { Transaction } 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 { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValue(undefined);

    const result = await run(db, { userId: "nonexistent-user" });
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(UserNotFoundError);
    }
  });

  it("throws when user is PENDING", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValue(pendingUser);

    const result = await run(db, { 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 { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValue(activeUser);

    const result = await run(db, { 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 { db, spies } = createMockDb<Transaction>();
    const reactivatedUser = {
      ...inactiveUser,
      status: "ACTIVE" as const,
      updatedAt: new Date("2024-01-15T00:00:00.000Z"),
    };

    spies.select.mockReturnValue(inactiveUser);
    spies.update.mockReturnValue(reactivatedUser);

    const result = await run(db, {
      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();
    }
    expect(spies.update).toHaveBeenCalled();
  });
});
