import { validatePurchaseCostProofFile, storePurchaseCostProof } from "@/features/purchases/lib/store-purchase-cost-proof";
import type { PurchaseInput } from "@/features/purchases/schemas/purchase.schema";

export async function buildPurchaseCostEntries(
  payload: PurchaseInput,
  costProofFiles: Array<{ index: number; file: File }>
) {
  const proofByIndex = new Map<number, string>();
  for (const proof of costProofFiles) {
    if (proof.file.size === 0) continue;
    const validationError = validatePurchaseCostProofFile(proof.file);
    if (validationError) {
      throw new Error(validationError);
    }
    const proofUrl = await storePurchaseCostProof(proof.file, proof.index);
    proofByIndex.set(proof.index, proofUrl);
  }

  return payload.cost_lines.map((costLine, index) => ({
    costType: costLine.cost_name.trim(),
    description: costLine.notes?.trim() || null,
    amount: costLine.amount,
    proofFileUrl: proofByIndex.get(index) ?? costLine.proof_file_url ?? null
  }));
}
