import { NextResponse } from "next/server";
import { sendUniversalEmailV2, EmailTypeV2 } from "@/lib/emailTemplateService";

export async function POST(req: Request) {
  try {
    const body = await req.json();
    const { to, subject, template, data, cc } = body;

    // Validation
    if (!to || !template) {
      return NextResponse.json(
        { error: "Les champs 'to' et 'template' sont requis" },
        { status: 400 }
      );
    }

    // Valider que le template est un EmailTypeV2 valide
    const validTypes: EmailTypeV2[] = [
      'contract-created',
      'contract-updated',
      'contract-cancelled',
      'employee-created',
      'invitation',
      'auto-declaration-invitation',
      'invoice',
      'signature-request',
      'signature-request-employer',
      'signature-request-employee',
      'signature-request-employee-amendment',
      'signature-request-salarie',
      'amendment-completed-employer',
      'amendment-completed-employee',
      'bulk-signature-notification',
      'salary-transfer-notification',
      'salary-transfer-payment-confirmation',
      'contribution-notification',
      'production-declared',
      'notification',
      'support-reply',
      'support-ticket-created',
      'support-ticket-reply',
      'contact-support',
      'contract-note-added',
      'referral',
      'account-activation',
      'access-updated',
      'access-revoked',
      'password-created',
      'password-changed',
      'twofa-enabled',
      'twofa-disabled',
    ];

    if (!validTypes.includes(template)) {
      return NextResponse.json(
        { error: `Type de template invalide: ${template}` },
        { status: 400 }
      );
    }

    // Préparer les données avec un discount par défaut pour le template referral
    const emailData = template === 'referral' 
      ? { ...data, discount: '20 € HT' }
      : data;

    // Envoyer l'email
    const messageId = await sendUniversalEmailV2({
      type: template as EmailTypeV2,
      toEmail: to,
      ccEmail: cc,
      subject,
      data: emailData,
    });

    return NextResponse.json({ 
      success: true, 
      messageId,
      message: "Email envoyé avec succès" 
    });
  } catch (error: any) {
    console.error("Erreur lors de l'envoi de l'email:", error);
    return NextResponse.json(
      { error: error.message || "Erreur lors de l'envoi de l'email" },
      { status: 500 }
    );
  }
}
