import { z } from "zod";

const zoomMeetingBase = z.object({
  topic: z.string().min(1, "Topic is required").max(200, "Topic is too long").optional(),
  startTimeIso: z.string().datetime().optional(),
  durationMinutes: z.number().int().positive().max(480).optional(), // Max 8 hours
  hostUserId: z.string().trim().optional(),
  fullName: z.string().min(1, "Full name is required").max(200, "Name is too long").trim(),
  email: z.string().email("Invalid email address").toLowerCase().trim(),
  preferredMeetingTime: z.string().min(1, "Preferred meeting time is required").trim(),
  projectDescription: z.string().optional().nullable(),
  additionalNotes: z.string().optional().nullable(),
  meetingType: z.string().optional().default("consultation"), // Default to consultation
  attendees: z.array(z.object({
    name: z.string().optional(),
    email: z.string().email().optional(),
  })).optional(),
  status: z.enum(["Scheduled", "Completed", "Cancelled", "In Progress"]).optional(),
  source: z.string().optional(), // Source domain: "abitsoft" or "abitsol"
});

const createZoomMeetingSchema = zoomMeetingBase;
const updateZoomMeetingSchema = zoomMeetingBase.partial().extend({
  zoomMeetingId: z.string().optional(),
  joinUrl: z.string().url().optional(),
  startUrl: z.string().url().optional(),
  meetingNumber: z.string().optional(),
  password: z.string().optional(),
});

function normalizeZoomMeetingPayload(payload) {
  if (!payload || typeof payload !== "object") {
    return {};
  }
  
  const normalized = { ...payload };
  
  // Normalize email to lowercase and trim
  if (normalized.email) {
    normalized.email = String(normalized.email).toLowerCase().trim();
  }
  
  // Normalize fullName - trim whitespace
  if (normalized.fullName) {
    normalized.fullName = String(normalized.fullName).trim();
  }
  
  // Normalize preferredMeetingTime - trim whitespace
  if (normalized.preferredMeetingTime) {
    normalized.preferredMeetingTime = String(normalized.preferredMeetingTime).trim();
  }
  
  // Normalize optional string fields - convert empty strings to undefined
  if (normalized.projectDescription !== undefined) {
    normalized.projectDescription = normalized.projectDescription 
      ? String(normalized.projectDescription).trim() 
      : undefined;
  }
  
  if (normalized.additionalNotes !== undefined) {
    normalized.additionalNotes = normalized.additionalNotes 
      ? String(normalized.additionalNotes).trim() 
      : undefined;
  }
  
  // Default meetingType to "consultation" if not provided
  if (!normalized.meetingType) {
    normalized.meetingType = "consultation";
  } else {
    normalized.meetingType = String(normalized.meetingType).trim();
  }
  
  // Normalize attendees emails
  if (Array.isArray(normalized.attendees)) {
    normalized.attendees = normalized.attendees.map(attendee => ({
      ...attendee,
      email: attendee.email ? String(attendee.email).toLowerCase().trim() : undefined,
      name: attendee.name ? String(attendee.name).trim() : undefined,
    }));
  }
  
  // Ensure duration is a number
  if (normalized.durationMinutes !== undefined) {
    normalized.durationMinutes = Number(normalized.durationMinutes);
    if (isNaN(normalized.durationMinutes)) {
      normalized.durationMinutes = undefined;
    }
  }
  
  return normalized;
}

// Schema for ScheduleZoom UI component
const scheduleZoomMeetingSchema = z.object({
  title: z.string().min(1, "Meeting title is required").max(200, "Title is too long"),
  description: z.string().optional(),
  date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/, "Date must be in YYYY-MM-DD format"),
  time: z.string().regex(/^\d{2}:\d{2}$/, "Time must be in HH:mm format"),
  duration: z.number().int().positive().max(480), // Max 8 hours
  timezone: z.string().min(1, "Timezone is required"),
  participants: z.string().min(1, "At least one participant email is required"),
  companyEmail: z.string().email("Invalid company email").optional(),
  meetingType: z.string().optional(),
  waitingRoom: z.boolean().optional().default(true),
  recordMeeting: z.boolean().optional().default(false),
  requirePassword: z.boolean().optional().default(false),
  autoStart: z.boolean().optional().default(false),
  joinBeforeHost: z.boolean().optional().default(false),
  muteUponEntry: z.boolean().optional().default(true),
  watermark: z.boolean().optional().default(false),
  usePersonalMeetingId: z.boolean().optional().default(false),
  source: z.string().optional(), // Source domain: "abitsoft" or "abitsol"
});

function normalizeScheduleZoomPayload(payload) {
  if (!payload || typeof payload !== "object") {
    return {};
  }
  
  const normalized = { ...payload };
  
  // Ensure duration is a number
  if (normalized.duration !== undefined) {
    normalized.duration = Number(normalized.duration);
  }
  
  // Normalize boolean fields
  const booleanFields = [
    'waitingRoom', 'recordMeeting', 'requirePassword', 'autoStart',
    'joinBeforeHost', 'muteUponEntry', 'watermark', 'usePersonalMeetingId'
  ];
  booleanFields.forEach(field => {
    if (normalized[field] !== undefined) {
      normalized[field] = Boolean(normalized[field]);
    }
  });
  
  // Normalize participants string (trim and lowercase emails)
  if (normalized.participants && typeof normalized.participants === 'string') {
    normalized.participants = normalized.participants
      .split(',')
      .map(email => email.trim().toLowerCase())
      .filter(Boolean)
      .join(',');
  }
  
  // Normalize company email
  if (normalized.companyEmail) {
    normalized.companyEmail = normalized.companyEmail.toLowerCase().trim();
  }
  
  return normalized;
}

export {
  createZoomMeetingSchema,
  updateZoomMeetingSchema,
  normalizeZoomMeetingPayload,
  scheduleZoomMeetingSchema,
  normalizeScheduleZoomPayload,
};

