import type { ClassifiedDeal } from "./types";

export type PropertyCsvField = { key: keyof ClassifiedDeal; label: string };

export const PROPERTY_CSV_FIELDS: PropertyCsvField[] = [
  { key: "dealname", label: "Address" },
  { key: "landlordPropertyId", label: "Property Ref" },
  { key: "uprn", label: "UPRN" },
  { key: "displayStage", label: "Stage" },
  { key: "projectCode", label: "Project" },
  { key: "coordinator", label: "Coordinator" },
  { key: "designer", label: "Designer" },
  { key: "installer", label: "Installer" },
  { key: "proposedMeasures", label: "Proposed Measures" },
  { key: "approvedPackage", label: "Approved Package" },
  { key: "actualMeasuresInstalled", label: "Installed Measures" },
  { key: "preSapScore", label: "Pre-SAP" },
  { key: "eiScore", label: "EI Score" },
  { key: "eiScorePotential", label: "EI Score (Potential)" },
  { key: "epcSapScore", label: "EPC SAP Score" },
  { key: "potentialPostSapScoreDropdown", label: "EPC SAP (Potential)" },
  { key: "lodgementStatus", label: "Lodgement Status" },
  { key: "surveyedDate", label: "Surveyed Date" },
  { key: "designDate", label: "Design Date" },
  { key: "fullLodgementDate", label: "Lodgement Date" },
  { key: "epcPrn", label: "EPC Certificate Number" },
  { key: "batch", label: "Group" },
  { key: "batchDescription", label: "Group Description" },
  { key: "coordinationComments", label: "Coordination Comments" },
  { key: "dampMouldFlag", label: "Damp and Mould Growth" },
  { key: "dampMouldAndRepairComments", label: "Damp Mould and Repair Comments" },
  { key: "domnasurveyRequired", label: "Domna Survey Required" },
  { key: "planningAuthority", label: "Planning Authority" },
  { key: "designatedArea", label: "Designated Area" },
  { key: "article4PdRights", label: "Article 4 PD Rights" },
  { key: "listedBuilding", label: "Listed Building" },
  { key: "designConstraints", label: "Design Constraints" },
  { key: "planningComments", label: "Planning Comments" },
  { key: "planningStatus", label: "Planning Status" },
  { key: "planningSuggestedApproach", label: "Planning Suggested Approach" },
];

export function escapeCsvCell(value: unknown): string {
  if (value === null || value === undefined) return "";
  const str =
    value instanceof Date
      ? value.toLocaleDateString("en-GB")
      : String(value);
  return str.includes(",") || str.includes('"') || str.includes("\n")
    ? `"${str.replace(/"/g, '""')}"`
    : str;
}

export function formatPropertyCsv(
  rows: ClassifiedDeal[],
  fields: PropertyCsvField[] = PROPERTY_CSV_FIELDS,
): string {
  const header = fields.map((f) => f.label).join(",");
  if (rows.length === 0) return header;
  const body = rows
    .map((row) => fields.map((f) => escapeCsvCell(row[f.key])).join(","))
    .join("\n");
  return header + "\n" + body;
}
