import { sendInterviewEmails } from "../services/interviewEmail.service.js";
import { successResponse, errorResponse } from "../utils/response.js";
import { HTTP_STATUS } from "../constants/index.js";
import logger from "../utils/logger.js";

/**
 * POST /api/interviews/send-email
 * Send interview confirmation emails to candidate and admin
 */
export const sendEmail = async (req, res, next) => {
  try {
    const {
      candidateName,
      candidateEmail,
      role,
      interviewDate,
      interviewType,
      interviewer,
      meetingUrl,
      location,
      notes,
    } = req.body;

    // Validate required fields
    if (!candidateName || !candidateEmail || !role || !interviewDate || !interviewType || !interviewer) {
      return errorResponse(
        res,
        "Missing required fields: candidateName, candidateEmail, role, interviewDate, interviewType, interviewer",
        HTTP_STATUS.BAD_REQUEST
      );
    }

    // Validate email format
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(candidateEmail)) {
      return errorResponse(res, "Invalid candidate email address", HTTP_STATUS.BAD_REQUEST);
    }

    // Validate interview type
    if (!["Remote", "Onsite"].includes(interviewType)) {
      return errorResponse(res, "Interview type must be 'Remote' or 'Onsite'", HTTP_STATUS.BAD_REQUEST);
    }

    // Validate meeting URL for remote interviews
    if (interviewType === "Remote" && !meetingUrl) {
      return errorResponse(res, "Meeting URL is required for remote interviews", HTTP_STATUS.BAD_REQUEST);
    }

    // Validate location for onsite interviews
    if (interviewType === "Onsite" && !location) {
      return errorResponse(res, "Location is required for onsite interviews", HTTP_STATUS.BAD_REQUEST);
    }

    // Send emails
    await sendInterviewEmails({
      candidateName: candidateName.trim(),
      candidateEmail: candidateEmail.trim().toLowerCase(),
      role: role.trim(),
      interviewDate: new Date(interviewDate),
      interviewType,
      interviewer: interviewer.trim(),
      meetingUrl: meetingUrl?.trim() || undefined,
      location: location?.trim() || undefined,
      notes: notes?.trim() || undefined,
    });

    logger.info(`Interview emails sent successfully for ${candidateName} - ${role}`);

    return successResponse(
      res,
      { message: "Interview confirmation emails sent successfully to candidate and admin" },
      HTTP_STATUS.OK
    );
  } catch (err) {
    logger.error("Error sending interview emails:", err);
    next(err);
  }
};

