import type { OnboardingStepData, ReviewConflict } from "./api-types";

const INCOME_MISMATCH_RATIO = 0.05;

function formatUzs(n: number): string {
  return new Intl.NumberFormat("uz-UZ").format(Math.round(n));
}

/** Detect mismatches between farmer-entered data and OCR / land totals. */
export function detectReviewConflicts(stepData: OnboardingStepData): ReviewConflict[] {
  const conflicts: ReviewConflict[] = [];
  const finance = stepData.FINANCE_REQUEST;
  const documents = stepData.DOCUMENTS;
  const land = stepData.LAND_SKETCH;
  const crops = stepData.CROP_PLAN;

  const ocrIncome = documents?.extractedFinancials?.monthlyIncomeUzs;
  const farmerIncome = finance?.monthlyIncomeUzs;
  if (
    ocrIncome != null &&
    farmerIncome != null &&
    ocrIncome > 0 &&
    Math.abs(farmerIncome - ocrIncome) / ocrIncome > INCOME_MISMATCH_RATIO
  ) {
    conflicts.push({
      id: "income_vs_ocr",
      type: "income_vs_ocr",
      label: "Monthly income differs from bank statement OCR",
      farmerValue: formatUzs(farmerIncome),
      documentValue: formatUzs(ocrIncome),
    });
  }

  const totalLandHa =
    land?.parcels?.reduce((sum, p) => sum + (p.areaHa ?? 0), 0) ?? 0;
  const cropAreaSum = crops?.crops?.reduce((sum, c) => sum + (c.areaHa ?? 0), 0) ?? 0;
  if (totalLandHa > 0 && cropAreaSum > totalLandHa + 0.001) {
    conflicts.push({
      id: "crop_area_vs_land",
      type: "crop_area_vs_land",
      label: "Total crop area exceeds declared land",
      farmerValue: `${cropAreaSum.toFixed(1)} ha`,
      documentValue: `${totalLandHa.toFixed(1)} ha`,
    });
  }

  return conflicts;
}

export function allConflictsResolved(conflicts: ReviewConflict[]): boolean {
  return conflicts.every((c) => c.resolution != null);
}
