import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import { Transaction } from "../generated/kysely-tailordb";
import { InvalidStatusTransitionError, RoleNotFoundError } from "../lib/errors.generated";
import { baseRole, inactiveRole } from "../testing/fixtures";
import { run } from "./reactivateRole";

describe("reactivateRole", () => {
  it("throws when role does not exist", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValue(undefined);

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

  it("throws when role is already ACTIVE", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValue(baseRole);

    const result = await run(db, { roleId: baseRole.id });
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(InvalidStatusTransitionError);
    }
  });

  it("reactivates INACTIVE role to ACTIVE", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const reactivatedRole = {
      ...inactiveRole,
      status: "ACTIVE" as const,
      updatedAt: new Date("2024-01-15T00:00:00.000Z"),
    };

    spies.select
      .mockReturnValueOnce(inactiveRole)
      // recomputePermissionsForUsersWithRole: query UserRole by roleId returns no users
      .mockReturnValueOnce([]);
    spies.update.mockReturnValue(reactivatedRole);

    const result = await run(db, { roleId: inactiveRole.id });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.role.status).toBe("ACTIVE");
      expect(result.value.role.updatedAt).not.toBeNull();
    }
    expect(spies.update).toHaveBeenCalled();
  });

  it("triggers recomputation of effective permissions", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const reactivatedRole = {
      ...inactiveRole,
      status: "ACTIVE" as const,
      updatedAt: new Date("2024-01-15T00:00:00.000Z"),
    };
    const updatedUser = {
      id: "user-active-1",
      permissions: [],
    };

    spies.select
      .mockReturnValueOnce(inactiveRole)
      // recomputePermissionsForUsersWithRole: query UserRole by roleId returns one user
      .mockReturnValueOnce([{ userId: "user-active-1" }])
      // recomputeUserPermissions: query permission keys for that user
      .mockReturnValueOnce([]);
    spies.update
      .mockReturnValueOnce(reactivatedRole)
      // recomputeUserPermissions: update user permissions
      .mockReturnValueOnce(updatedUser);

    const result = await run(db, { roleId: inactiveRole.id });

    expect(result.ok).toBe(true);
    // Role update + user permission recompute update
    expect(spies.update).toHaveBeenCalledTimes(2);
  });
});
