import { err, ok } from "@tailor-platform/erp-kit/core";
import { roleLifecycle } from "../db/role.lifecycle.generated";
import { Transaction } from "../generated/kysely-tailordb";
import { InvalidStatusTransitionError, RoleNotFoundError } from "../lib/errors.generated";
import { recomputePermissionsForUsersWithRole } from "../lib/recomputeUserPermissions";

export interface ReactivateRoleInput {
  roleId: string;
}

/**
 * Function: reactivateRole
 *
 * Transitions a role from INACTIVE back to ACTIVE status.
 * Recomputes effective permissions for all users assigned this role.
 */
export async function run(db: Transaction, input: ReactivateRoleInput) {
  const role = await db
    .selectFrom("Role")
    .selectAll()
    .where("id", "=", input.roleId)
    .forUpdate()
    .executeTakeFirst();

  if (!role) {
    return err(new RoleNotFoundError(input.roleId));
  }

  const nextStatus = roleLifecycle.tryTransition(role.status, "reactivate");
  if (!nextStatus) {
    return err(new InvalidStatusTransitionError(input.roleId));
  }

  const updatedRole = await db
    .updateTable("Role")
    .set({
      status: nextStatus,
    })
    .where("id", "=", input.roleId)
    .returningAll()
    .executeTakeFirstOrThrow();

  await recomputePermissionsForUsersWithRole(db, input.roleId);

  return ok({ role: updatedRole });
}
