// formSchemas.ts
import * as z from "zod";
import { MeasureKeyEnum, HousingType } from "@/app/db/schema/recommendations";

export const baseFormSchema = z.object({
  measures: z.array(MeasureKeyEnum).min(1, "At least one measure is required"),
});

export type BaseFormValues = z.infer<typeof baseFormSchema>;

export const RemoteAssessmentFormSchema = baseFormSchema
  .extend({
    scenario: z.string().min(1),
    goal: z.string().min(1),
    // goalValue: z.string().min(1),
    goalValue: z.string().optional(),
    budget: z.number().optional(),
    housingType: z.enum(HousingType),
    addressLineOne: z.string().min(1),
    postcode: z.string().min(1),
    uprn: z.number().min(1, "UPRN must be a valid number"),
    valuation: z.number().min(1, "Valuation must be a valid number").optional(),
    propertyType: z.string().nullable().optional(),
    builtForm: z.string().nullable().optional(),
  })
  .refine((data) => data.goal !== "Increasing EPC" || !!data.goalValue, {
    path: ["goalValue"],
    message: "Target EPC Rating is required when goal is Increasing EPC",
  })
  .refine(
    (data) =>
      data.goal === "Increasing EPC" ||
      (typeof data.budget === "number" && data.budget > 0),
    {
      path: ["budget"],
      message: "Budget is required for this goal",
    }
  );

export type RemoteAssessmentFormValues = z.infer<
  typeof RemoteAssessmentFormSchema
>;

export const uploadCsvSchema = baseFormSchema.extend({
  scenario: z.string().min(1),
  goal: z.string().min(1),
  goalValue: z.string().min(1),
  housingType: z.string(),
  ashpCop: z.preprocess((val) => {
    if (val === "" || val === undefined) return undefined;
    return Number(val);
  }, z.number().min(0.1)),
  budget: z.preprocess(
    (val) => {
      if (val === "" || val === undefined) return undefined;
      if (val === null) return null;
      return Number(val);
    },
    z.union([z.number(), z.null()]).optional()
  ),
  enforce_fabric_first: z.boolean().default(false),
});

export type UploadCsvFormValues = z.infer<typeof uploadCsvSchema>;
