
"use server";

import { z } from 'zod';
import nodemailer from 'nodemailer';

const LeadSchema = z.object({
  name: z.string().min(2, "Name must be at least 2 characters."),
  email: z.string().email("Invalid email address."),
  company: z.string().optional(),
  phone: z.string().min(10, "Phone number must be at least 10 digits."),
  message: z.string().optional(),
  formType: z.string(),
  productName: z.string().optional(),
});

/**
 * Shared helper to create a nodemailer transporter using environment variables.
 */
function getTransporter() {
  return nodemailer.createTransport({
    host: process.env.EMAIL_SERVER_HOST,
    port: Number(process.env.EMAIL_SERVER_PORT),
    secure: Number(process.env.EMAIL_SERVER_PORT) === 465, // true for 465, false for other ports
    auth: {
      user: process.env.EMAIL_SERVER_USER,
      pass: process.env.EMAIL_SERVER_PASSWORD,
    },
  });
}

export async function submitLead(formData: FormData) {
  const rawData = Object.fromEntries(formData.entries());

  const validatedFields = LeadSchema.safeParse(rawData);

  if (!validatedFields.success) {
    console.error("[Email Log] Validation failed for lead submission:", validatedFields.error.flatten().fieldErrors);
    return {
      errors: validatedFields.error.flatten().fieldErrors,
      message: 'Validation failed. Please check your input.',
    };
  }

  const { name, email, company, phone, message, formType, productName } = validatedFields.data;

  const transporter = getTransporter();

  const mailOptions = {
    from: process.env.EMAIL_FROM,
    to: process.env.EMAIL_TO,
    subject: `New Lead Submission: ${formType}`,
    html: `
      <h2>New Lead Submission</h2>
      <p><strong>Form Type:</strong> ${formType}</p>
      ${productName ? `<p><strong>Product/Service of Interest:</strong> ${productName}</p>`: ''}
      <p><strong>Name:</strong> ${name}</p>
      <p><strong>Email:</strong> ${email}</p>
      <p><strong>Phone:</strong> ${phone}</p>
      ${company ? `<p><strong>Company:</strong> ${company}</p>` : ''}
      ${message ? `<h3>Message:</h3><p>${message}</p>` : ''}
    `,
  };

  console.log("[Email Log] Attempting to send Lead Submission email:", {
    to: process.env.EMAIL_TO,
    formType,
    data: validatedFields.data
  });

  try {
    const info = await transporter.sendMail(mailOptions);
    console.log("[Email Log] SUCCESS: Lead email sent.", {
      messageId: info.messageId,
      response: info.response,
      recipient: process.env.EMAIL_TO,
      payload: validatedFields.data
    });
    return {
      success: true,
      message: 'Thank you for your submission! We will get back to you shortly.',
    };
  } catch (error) {
    console.error("[Email Log] ERROR: Failed to send lead email.", {
      error: error instanceof Error ? error.message : error,
      recipient: process.env.EMAIL_TO,
      payload: validatedFields.data
    });
    return {
      success: false,
      message: 'There was an issue submitting your request. Please try again later.',
    };
  }
}

export async function recordCallInitiated(data: { name: string; email: string; phone: string }) {
  const transporter = getTransporter();
  const timestamp = new Date().toLocaleString('en-IN', { timeZone: 'Asia/Kolkata' });

  const mailOptions = {
    from: process.env.EMAIL_FROM,
    to: process.env.EMAIL_TO,
    subject: `[Call Log] Call Initiated: ${data.name}`,
    html: `
      <div style="font-family: sans-serif; max-width: 600px; margin: 0 auto; border: 1px solid #e2e8f0; border-radius: 8px; overflow: hidden;">
        <div style="background-color: #1A4B8A; color: white; padding: 20px; text-align: center;">
          <h2 style="margin: 0;">Call Request Log</h2>
        </div>
        <div style="padding: 24px; color: #1e293b;">
          <p>A new call has been initiated through the website widget.</p>
          <hr style="border: 0; border-top: 1px solid #e2e8f0; margin: 20px 0;">
          <p><strong>Customer Name:</strong> ${data.name}</p>
          <p><strong>Email Address:</strong> ${data.email}</p>
          <p><strong>Phone Number:</strong> ${data.phone}</p>
          <p><strong>Time (IST):</strong> ${timestamp}</p>
          <hr style="border: 0; border-top: 1px solid #e2e8f0; margin: 20px 0;">
          <p style="font-size: 14px; color: #64748b;">This log confirms that the Click-to-Call API was triggered for this contact.</p>
        </div>
      </div>
    `,
  };

  console.log("[Email Log] Attempting to send Call Initiation Record email:", {
    to: process.env.EMAIL_TO,
    customer: data.name,
    timestamp
  });

  try {
    const info = await transporter.sendMail(mailOptions);
    console.log("[Email Log] SUCCESS: Call initiation record email sent.", {
      messageId: info.messageId,
      response: info.response,
      recipient: process.env.EMAIL_TO,
      payload: data
    });
    return { success: true };
  } catch (error) {
    console.error("[Email Log] ERROR: Failed to send call initiation record email.", {
      error: error instanceof Error ? error.message : error,
      recipient: process.env.EMAIL_TO,
      payload: data
    });
    return { success: false };
  }
}
