import { z } from "zod";

const ApplicationStatusEnum = z.enum(["New", "Reviewed", "Interview", "Rejected"]);

const applicationBase = z.object({
  fullName: z.string().min(1, "Full name is required").max(200, "Full name is too long"),
  email: z.string().email("Invalid email address"),
  phone: z.string().optional(),
  jobId: z.union([z.string(), z.null()]).optional(),
  role: z.string().min(1, "Role is required").max(200, "Role is too long"),
  location: z.string().min(1, "Location is required").max(100, "Location is too long"),
  resumeUrl: z.union([z.string().url("Invalid resume URL"), z.literal("")]).optional(),
  note: z.string().max(1000, "Note is too long").optional(),
  status: ApplicationStatusEnum.default("New"),
  avatar: z.union([z.string().url("Invalid avatar URL"), z.literal("")]).optional(),
});

const createApplicationSchema = applicationBase;
const updateApplicationSchema = applicationBase.partial();

function normalizeApplicationPayload(payload) {
  if (!payload || typeof payload !== "object") {
    return {};
  }

  const normalized = { ...payload };

  // Normalize optional fields
  if (normalized.resumeUrl === "") {
    normalized.resumeUrl = undefined;
  }
  if (normalized.avatar === "") {
    normalized.avatar = undefined;
  }
  if (normalized.phone === "") {
    normalized.phone = undefined;
  }
  if (normalized.note === "") {
    normalized.note = undefined;
  }
  // Handle jobId - convert empty string or "general" to null
  if (normalized.jobId === "" || normalized.jobId === "general") {
    normalized.jobId = null;
  }

  return normalized;
}

export {
  ApplicationStatusEnum,
  createApplicationSchema,
  updateApplicationSchema,
  normalizeApplicationPayload,
};

