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

export interface DeactivateUserInput {
  userId: string;
  from?: string[];
}

/**
 * Function: deactivateUser
 *
 * Transitions a user from ACTIVE to INACTIVE status.
 * Role assignments are preserved.
 */
export async function run(db: Transaction, input: DeactivateUserInput) {
  const user = await db
    .selectFrom("User")
    .selectAll()
    .where("id", "=", input.userId)
    .forUpdate()
    .executeTakeFirst();

  if (!user) {
    return err(new UserNotFoundError(input.userId));
  }

  const validFromStatuses = input.from ?? ["ACTIVE"];
  if (!validFromStatuses.includes(user.status)) {
    return err(new InvalidStatusTransitionError(`${user.status} to INACTIVE`));
  }

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

  return ok({ user: updatedUser! });
}
