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

export interface FinalizeVarianceReportInput {
  varianceReportId: string;
}

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

  // Validate report exists
  const report = (await db
    .selectFrom("VarianceReport")
    .where("id" as never, "=", input.varianceReportId as never)
    .selectAll()
    .forUpdate()
    .executeTakeFirst()) as Record<string, unknown> | undefined;

  if (!report) {
    return err(new VarianceReportNotFoundError(input.varianceReportId));
  }

  // Validate report is in DRAFT status
  if (report.status !== "DRAFT") {
    return err(new InvalidStateError(input.varianceReportId));
  }

  // Transition to FINAL status
  const updatedReport = await db
    .updateTable("VarianceReport" as never)
    .set({
      status: "FINAL",
      updatedAt: new Date(),
    } as never)
    .where("id" as never, "=", input.varianceReportId as never)
    .returningAll()
    .executeTakeFirst();

  return ok({ varianceReport: updatedReport! });
}
