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

describe("deactivateRole", () => {
  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 INACTIVE", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValue(inactiveRole);

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

  it("throws when role has active user assignments", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(baseRole)
      // UserRole query returns active assignments
      .mockReturnValueOnce([baseUserRole]);

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

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

    spies.select
      .mockReturnValueOnce(baseRole)
      // No active UserRole assignments
      .mockReturnValueOnce([])
      // recomputePermissionsForUsersWithRole: query UserRole by roleId
      .mockReturnValueOnce([]);
    spies.update.mockReturnValue(deactivatedRole);

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

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

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

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

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

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