export const prerender = false;

import type { APIRoute } from 'astro';
import { Resend } from 'resend';

const resendApiKey = import.meta.env.RESEND_API_KEY;
const resend = resendApiKey ? new Resend(resendApiKey) : null;

export const POST: APIRoute = async ({ request }) => {
  try {
    const { event, pin, email } = await request.json();
    
    if (!event || !pin || !email) {
      return new Response(JSON.stringify({ error: 'Event, PIN, and email are required' }), {
        status: 400,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    // Validate PIN format
    if (!/^\d{4}$/.test(pin)) {
      return new Response(JSON.stringify({ error: 'PIN must be exactly 4 digits' }), {
        status: 400,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    // Check if Resend is configured
    if (!resend) {

      return new Response(JSON.stringify({ error: 'Email service not configured' }), {
        status: 500,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    // Send email with PIN
    const { data, error } = await resend.emails.send({
      from: 'Black Canyon Tickets <noreply@blackcanyontickets.com>',
      to: [email],
      subject: `Sales Kiosk PIN for ${event.title}`,
      html: `
        <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px;">
          <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 30px; border-radius: 10px 10px 0 0; text-align: center;">
            <h1 style="margin: 0; font-size: 24px;">🔐 Sales Kiosk PIN</h1>
            <p style="margin: 10px 0 0 0; opacity: 0.9;">Black Canyon Tickets</p>
          </div>
          
          <div style="background: #f8f9fa; padding: 30px; border-radius: 0 0 10px 10px; border: 1px solid #e9ecef;">
            <h2 style="color: #333; margin-top: 0;">Your Sales Kiosk PIN</h2>
            
            <div style="background: white; padding: 20px; border-radius: 8px; border: 1px solid #e9ecef; margin: 20px 0;">
              <p style="margin: 0 0 10px 0; color: #666;"><strong>Event:</strong> ${event.title}</p>
              <p style="margin: 0 0 20px 0; color: #666;"><strong>Generated:</strong> ${new Date().toLocaleString()}</p>
              
              <div style="text-align: center; margin: 30px 0;">
                <div style="background: #f1f3f4; padding: 20px; border-radius: 8px; display: inline-block;">
                  <p style="margin: 0 0 10px 0; color: #666; font-size: 14px;">Your 4-digit PIN</p>
                  <p style="margin: 0; font-size: 36px; font-weight: bold; color: #333; letter-spacing: 8px; font-family: monospace;">${pin}</p>
                </div>
              </div>
            </div>
            
            <div style="background: #e3f2fd; padding: 15px; border-radius: 8px; border-left: 4px solid #2196f3; margin: 20px 0;">
              <h3 style="margin: 0 0 10px 0; color: #1976d2; font-size: 16px;">📱 How to Use</h3>
              <ol style="margin: 0; padding-left: 20px; color: #666;">
                <li>Navigate to the sales kiosk URL</li>
                <li>Enter this 4-digit PIN when prompted</li>
                <li>Access the touchscreen sales interface</li>
                <li>Lock the kiosk when finished</li>
              </ol>
            </div>
            
            <div style="background: #fff3e0; padding: 15px; border-radius: 8px; border-left: 4px solid #ff9800; margin: 20px 0;">
              <h3 style="margin: 0 0 10px 0; color: #f57c00; font-size: 16px;">⚠️ Important Notes</h3>
              <ul style="margin: 0; padding-left: 20px; color: #666;">
                <li><strong>Security:</strong> This PIN expires in 24 hours</li>
                <li><strong>Access:</strong> Only share with authorized staff</li>
                <li><strong>Locking:</strong> Always lock the kiosk when not in use</li>
                <li><strong>Support:</strong> Generate a new PIN if needed</li>
              </ul>
            </div>
            
            <div style="text-align: center; margin: 30px 0;">
              <a href="https://portal.blackcanyontickets.com/events/${event.id}/manage" 
                 style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 12px 30px; text-decoration: none; border-radius: 6px; font-weight: bold; display: inline-block;">
                Manage Event
              </a>
            </div>
            
            <p style="color: #666; font-size: 12px; text-align: center; margin: 30px 0 0 0;">
              This PIN was generated automatically by Black Canyon Tickets.<br>
              If you did not request this PIN, please contact support immediately.
            </p>
          </div>
        </div>
      `
    });

    if (error) {

      return new Response(JSON.stringify({ error: 'Failed to send PIN email' }), {
        status: 500,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    return new Response(JSON.stringify({ 
      success: true, 
      emailId: data?.id 
    }), {
      status: 200,
      headers: { 'Content-Type': 'application/json' }
    });

  } catch (error) {

    return new Response(JSON.stringify({ error: 'Internal server error' }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
};