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

export interface GetManufacturingCostSummaryInput {
  id?: string;
  productionOrderId?: string;
}

export async function run(db: ReadonlyDB<DB>, input: GetManufacturingCostSummaryInput) {
  let query = db.selectFrom("ManufacturingCostSummary").selectAll();

  if (input.id) {
    query = query.where("id", "=", input.id);
  } else if (input.productionOrderId) {
    query = query.where("productionOrderId", "=", input.productionOrderId);
  } else {
    return err(new CostSummaryNotFoundError("no id or productionOrderId provided"));
  }

  const costSummary = await query.executeTakeFirst();

  if (!costSummary) {
    return err(new CostSummaryNotFoundError(input.id ?? input.productionOrderId ?? "unknown"));
  }

  const costLines = await db
    .selectFrom("ManufacturingCostLine")
    .selectAll()
    .where("costSummaryId", "=", costSummary.id)
    .execute();

  const varianceLines = await db
    .selectFrom("CostVarianceLine")
    .selectAll()
    .where("costSummaryId", "=", costSummary.id)
    .execute();

  const settlementRecords = await db
    .selectFrom("ManufacturingCostSettlementRecord")
    .selectAll()
    .where("costSummaryId", "=", costSummary.id)
    .execute();

  return ok({ costSummary, costLines, varianceLines, settlementRecords });
}
