import { z } from "zod";
import { EMPLOYMENT_TYPES, JOB_STATUS } from "../constants/index.js";

const EmploymentTypeEnum = z.enum(EMPLOYMENT_TYPES);
const JobStatusEnum = z.enum(JOB_STATUS);

const jobBase = z.object({
  title: z.string().min(1, "Title is required").max(200, "Title is too long"),
  department: z.string().min(1, "Department is required"),
  location: z.string().min(1, "Location is required").max(100, "Location is too long"),
  employmentType: EmploymentTypeEnum,
  description: z.string().min(1, "Description is required"),
  responsibilities: z.array(z.string()).default([]),
  requirements: z.array(z.string()).default([]),
  applicationUrl: z.string().url("Invalid application URL"),
  tags: z.union([z.string(), z.array(z.string())]).default(""),
  status: JobStatusEnum,
});

const createJobSchema = jobBase;
const updateJobSchema = jobBase.partial();

function normalizeJobPayload(payload) {
  if (!payload || typeof payload !== "object") {
    return {};
  }
  
  const normalized = { ...payload };
  
  // Normalize tags: convert string to array
  if (typeof normalized.tags === "string") {
    const parts = normalized.tags
      .split(",")
      .map((s) => s.trim())
      .filter(Boolean);
    normalized.tags = parts.length > 0 ? parts : [];
  } else if (!Array.isArray(normalized.tags)) {
    normalized.tags = [];
  }
  
  // Ensure responsibilities is an array
  if (!Array.isArray(normalized.responsibilities)) {
    normalized.responsibilities = [];
  }
  // Filter out empty strings
  normalized.responsibilities = normalized.responsibilities.filter((r) => r && r.trim());
  
  // Ensure requirements is an array
  if (!Array.isArray(normalized.requirements)) {
    normalized.requirements = [];
  }
  // Filter out empty strings
  normalized.requirements = normalized.requirements.filter((r) => r && r.trim());
  
  return normalized;
}

export {
  EmploymentTypeEnum,
  JobStatusEnum,
  createJobSchema,
  updateJobSchema,
  normalizeJobPayload,
};


