import { isValid, parse } from "date-fns";

export function localDateTimeToUtcIso(
  date: string | Date | null | undefined,
  time?: string | null
): string | undefined {
  if (!date || !time) return undefined;

  let localDate: Date | null = null;

  if (date instanceof Date) {
    localDate = new Date(date);
  } else if (typeof date === "string") {
    const cleanDate = date.split(",")[0].trim();

    // Try supported formats (order matters)
    const formats = [
      "dd MMM yyyy", // 19 Dec 2025
      "dd-MM-yyyy",  // 19-12-2025
      "yyyy-MM-dd",  // 2025-12-19
    ];

    for (const format of formats) {
      const parsed = parse(cleanDate, format, new Date());
      if (isValid(parsed)) {
        localDate = parsed;
        break;
      }
    }
  }

  if (!localDate || !isValid(localDate)) return undefined;

  const [hours, minutes] = time.split(":").map(Number);

  if (Number.isNaN(hours) || Number.isNaN(minutes)) return undefined;

  // Apply local time
  localDate.setHours(hours, minutes, 0, 0);

  // Convert to UTC ISO
  return localDate.toISOString();
}
