import { NextRequest, NextResponse } from 'next/server';
import nodemailer from 'nodemailer';

// Mock data - in real app, fetch from database
const mockCertificates = [
  {
    id: '1',
    recipientName: 'Andi Wijaya',
    recipientEmail: 'andi.wijaya@trainee.dapurmbg.com',
    courseName: 'Teknik Dasar Memasak',
    completionDate: '2024-01-15',
    certificateNumber: 'MBG-TDM-2024-001',
    score: 92,
    status: 'issued',
    issuedBy: 'Chef Ahmad Fauzi',
    templateId: 'template-1',
    notes: 'Peserta menunjukkan kemampuan memasak dasar yang sangat baik.'
  },
];

export async function POST(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const { id } = params;
    const certificate = mockCertificates.find(cert => cert.id === id);

    if (!certificate) {
      return NextResponse.json(
        { error: 'Sertifikat tidak ditemukan' },
        { status: 404 }
      );
    }

    if (certificate.status !== 'issued') {
      return NextResponse.json(
        { error: 'Sertifikat belum diterbitkan' },
        { status: 400 }
      );
    }

    // Create transporter (using Gmail as example - configure for your needs)
    const transporter = nodemailer.createTransport({
      host: 'smtp.example.com', // Ganti dengan host SMTP Anda
      port: 587,
      secure: false,
      auth: {
        user: process.env.EMAIL_USER,
        pass: process.env.EMAIL_PASS,
      },
    });

    // Email content
    const mailOptions = {
      from: process.env.EMAIL_USER || 'your-email@gmail.com',
      to: certificate.recipientEmail,
      subject: `Sertifikat Penyelesaian - ${certificate.courseName}`,
      html: `
        <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
          <h2 style="color: #1e40af; text-align: center;">Selamat!</h2>
          <p>Halo <strong>${certificate.recipientName}</strong>,</p>
          <p>Selamat atas penyelesaian kursus <strong>${certificate.courseName}</strong>!</p>
          <p>
            Kami dengan senang hati mengirimkan sertifikat penyelesaian Anda. 
            Nomor sertifikat: <strong>${certificate.certificateNumber}</strong>
          </p>
          <p>
            Anda dapat mengunduh sertifikat Anda melalui tautan berikut:
            <br>
            <a href="${process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3003'}/admin/certificates/${certificate.id}" 
               style="display: inline-block; background-color: #1e40af; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px; margin-top: 10px;">
              Lihat Sertifikat
            </a>
          </p>
          <p>Terima kasih atas partisipasi Anda dalam kursus ini.</p>
          <hr style="border: 1px solid #e5e7eb; margin: 20px 0;">
          <p style="font-size: 12px; color: #6b7280; text-align: center;">
            Email ini dikirim otomatis oleh sistem LMS kami.
          </p>
        </div>
      `,
    };

    // Send email
    await transporter.sendMail(mailOptions);

    return NextResponse.json({
      success: true,
      message: 'Email sertifikat berhasil dikirim ulang',
      data: {
        id: certificate.id,
        recipientEmail: certificate.recipientEmail,
        sentAt: new Date().toISOString(),
      }
    });

  } catch (error) {
    console.error('Error resending certificate email:', error);
    return NextResponse.json(
      { error: 'Gagal mengirim email sertifikat' },
      { status: 500 }
    );
  }
}