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

export interface ActivateProfitCenterInput {
  profitCenterId: string;
  from?: string[];
}

export async function run(db: Transaction, input: ActivateProfitCenterInput, ctx: CommandContext) {
  void ctx;

  const validFromStatuses = input.from ?? ["DRAFT"];

  const profitCenter = await db
    .selectFrom("ProfitCenter")
    .selectAll()
    .where("id", "=", input.profitCenterId)
    .forUpdate()
    .executeTakeFirst();

  if (!profitCenter) {
    return err(new ProfitCenterNotFoundError(input.profitCenterId));
  }

  if (!validFromStatuses.includes(profitCenter.status)) {
    return err(new InvalidStateError(input.profitCenterId));
  }

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

  return ok({ profitCenter: updated! });
}
