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

export interface DeactivateRoleInput {
  roleId: string;
  from?: string[];
}

/**
 * Function: deactivateRole
 *
 * Transitions a role from ACTIVE to INACTIVE status.
 * Blocked if the role still has active UserRole assignments.
 */
export async function run(db: Transaction, input: DeactivateRoleInput) {
  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 ?? ["ACTIVE"];
  if (!validFromStatuses.includes(role.status)) {
    return err(new InvalidStatusTransitionError(`${role.status} to INACTIVE`));
  }

  const activeAssignments = await db
    .selectFrom("UserRole")
    .selectAll()
    .where("roleId", "=", input.roleId)
    .execute();

  if (activeAssignments.length > 0) {
    return err(new RoleHasActiveAssignmentsError(input.roleId));
  }

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

  await recomputePermissionsForUsersWithRole(db, input.roleId);

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