import { NextResponse } from "next/server";
import { NextRequest } from "next/server";
import { z } from "zod";
import { sendCourseInquiry } from "@/infrastructure/email/smtp";

const courseInquirySchema = z.object({
  name: z.string().min(2, "El nombre debe tener al menos 2 caracteres"),
  email: z.string().email("Email inválido"),
  course: z.string().min(1, "Debe seleccionar un curso"),
  message: z.string().min(10, "El mensaje debe tener al menos 10 caracteres"),
});

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();

    const validatedData = courseInquirySchema.parse(body);

    const adminEmail = process.env.ADMIN_EMAIL;
    if (!adminEmail) {
      return NextResponse.json(
        { success: false, message: "Email del administrador no configurado" },
        { status: 500 }
      );
    }

    await sendCourseInquiry(
      adminEmail,
      validatedData.name,
      validatedData.email,
      validatedData.course,
      validatedData.message
    );

    return NextResponse.json({
      success: true,
      message: "Consulta enviada exitosamente. Te contactaremos pronto.",
    });
  } catch (error) {
    if (error instanceof z.ZodError) {
      return NextResponse.json(
        {
          success: false,
          message: "Datos inválidos",
          errors: error.errors.map((e) => ({
            field: e.path.join("."),
            message: e.message,
          })),
        },
        { status: 400 }
      );
    }

    console.error("[Course Inquiry] Error:", error);
    return NextResponse.json(
      { success: false, message: "Error al enviar la consulta" },
      { status: 500 }
    );
  }
}
