import type { DB } from "../generated/kysely-tailordb";
import { ok, type ReadonlyDB } from "@tailor-platform/erp-kit/module";

export interface GetVarianceReportInput {
  id: string;
}

/**
 * Function: getVarianceReport
 *
 * Retrieves a single variance report by id, along with its report lines.
 */
export async function run(db: ReadonlyDB<DB>, input: GetVarianceReportInput) {
  const varianceReport = await db
    .selectFrom("VarianceReport")
    .selectAll()
    .where("id", "=", input.id)
    .executeTakeFirst();

  if (!varianceReport) {
    return ok({ varianceReport: null, lines: [] });
  }

  const lines = await db
    .selectFrom("VarianceReportLine")
    .selectAll()
    .where("varianceReportId", "=", input.id)
    .execute();

  return ok({ varianceReport, lines });
}
