/**
 * 공통 폼 유효성 검증 + 자동 포맷팅 유틸리티
 */

// --- 자동 포맷팅 ---

// 전화번호: 숫자만 추출 → 자동 하이픈
// 010-1234-5678(휴대폰 11자리) / 02-xxx-xxxx / 02-xxxx-xxxx
// 지역번호 10자리(032-672-1418) → 3-3-4 / 11자리(031-1234-5678) → 3-4-4
export function formatPhone(value: string): string {
  const nums = value.replace(/\D/g, "").slice(0, 11);
  if (nums.startsWith("02")) {
    if (nums.length <= 2) return nums;
    if (nums.length <= 5) return `${nums.slice(0, 2)}-${nums.slice(2)}`;
    if (nums.length <= 9) return `${nums.slice(0, 2)}-${nums.slice(2, 5)}-${nums.slice(5)}`;
    return `${nums.slice(0, 2)}-${nums.slice(2, 6)}-${nums.slice(6)}`;
  }
  if (nums.length <= 3) return nums;
  if (nums.length <= 6) return `${nums.slice(0, 3)}-${nums.slice(3)}`;
  if (nums.length <= 10) return `${nums.slice(0, 3)}-${nums.slice(3, 6)}-${nums.slice(6)}`;
  return `${nums.slice(0, 3)}-${nums.slice(3, 7)}-${nums.slice(7)}`;
}

// 사업자번호: 000-00-00000
export function formatBusinessNumber(value: string): string {
  const nums = value.replace(/\D/g, "").slice(0, 10);
  if (nums.length <= 3) return nums;
  if (nums.length <= 5) return `${nums.slice(0, 3)}-${nums.slice(3)}`;
  return `${nums.slice(0, 3)}-${nums.slice(3, 5)}-${nums.slice(5)}`;
}

// 필드명으로 자동 포맷팅
export function formatField(fieldName: string, value: string): string {
  switch (fieldName) {
    case "contact_phone":
    case "phone":
    case "cell_phone":
      return formatPhone(value);
    case "business_number":
      return formatBusinessNumber(value);
    default:
      return value;
  }
}

// --- 유효성 검증 ---

export function validatePhone(value: string): string | null {
  if (!value) return null;
  const nums = value.replace(/\D/g, "");
  if (nums.length < 9) return "전화번호를 끝까지 입력해주세요";
  return null;
}

export function validateEmail(value: string): string | null {
  if (!value) return null;
  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) return "올바른 이메일 형식이 아닙니다";
  return null;
}

export function validateBusinessNumber(value: string): string | null {
  if (!value) return null;
  const nums = value.replace(/\D/g, "");
  if (nums.length < 10) return "사업자번호를 끝까지 입력해주세요";
  return null;
}

export function validateField(fieldName: string, value: string): string | null {
  if (!value) return null;
  switch (fieldName) {
    case "contact_phone":
    case "phone":
    case "cell_phone":
      return validatePhone(value);
    case "email":
      return validateEmail(value);
    case "business_number":
      return validateBusinessNumber(value);
    default:
      return null;
  }
}

export function validateForm(
  data: Record<string, any>,
  fields: string[]
): Record<string, string> {
  const errors: Record<string, string> = {};
  for (const field of fields) {
    const error = validateField(field, data[field] || "");
    if (error) errors[field] = error;
  }
  return errors;
}
