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

export interface ReactivateRoleInput {
  roleId: string;
  from?: 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 validFromStatuses = input.from ?? ["INACTIVE"];
  if (!validFromStatuses.includes(role.status)) {
    return err(new InvalidStatusTransitionError(`${role.status} to ACTIVE`));
  }

  const updatedRole = await db
    .updateTable("Role")
    .set({
      status: "ACTIVE",
      updatedAt: new Date(),
    })
    .where("id", "=", input.roleId)
    .returningAll()
    .executeTakeFirst();

  await recomputePermissionsForUsersWithRole(db, input.roleId);

  return ok({ role: updatedRole! });
}
