import { executeTransition, ok } from "@tailor-platform/erp-kit/core";
import { userLifecycle } from "../db/user.lifecycle.generated";
import { Transaction } from "../generated/kysely-tailordb";
import { InvalidStatusTransitionError, UserNotFoundError } from "../lib/errors.generated";
import { recomputeUserPermissions } from "../lib/recomputeUserPermissions";

export interface DeactivateUserInput {
  userId: string;
}

/**
 * Function: deactivateUser
 *
 * Transitions a user from ACTIVE to INACTIVE status.
 * Role assignments are preserved.
 */
export async function run(db: Transaction, input: DeactivateUserInput) {
  const result = await executeTransition({
    db,
    tableName: "User",
    statusField: "status",
    id: input.userId,
    transition: "deactivate",
    lifecycle: userLifecycle,
    errors: { notFound: UserNotFoundError, invalidTransition: InvalidStatusTransitionError },
  });
  if (!result.ok) return result;
  const user = await recomputeUserPermissions(db, input.userId);
  return ok({ user });
}
