export const dynamic = 'force-dynamic';

import { NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';

export async function POST(request: Request) {
  try {
    const data = await request?.json?.();
    const name = data?.name ?? '';
    const email = data?.email ?? '';
    const phone = data?.phone ?? '';
    const subject = data?.subject ?? '';
    const message = data?.message ?? '';

    if (!name || !email || !subject || !message) {
      return NextResponse.json(
        { success: false, message: 'Please fill in all required fields.' },
        { status: 400 }
      );
    }

    // Save to database
    await prisma.contactSubmission.create({
      data: { name, email, phone, subject, message },
    });

    // Send notification email
    try {
      const appUrl = process.env.NEXTAUTH_URL ?? '';
      let appName = 'TradeTheMarkets';
      try {
        appName = appUrl ? new URL(appUrl)?.hostname?.split?.('.')?.[0] ?? 'TradeTheMarkets' : 'TradeTheMarkets';
      } catch { /* ignore */ }

      const htmlBody = `
        <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
          <div style="background: #0D1B3E; padding: 20px; text-align: center;">
            <h1 style="color: #C9940A; margin: 0; font-size: 22px;">TradeTheMarkets.co.uk</h1>
            <p style="color: #ffffff80; margin: 5px 0 0; font-size: 13px;">New Contact Form Submission</p>
          </div>
          <div style="background: #f9fafb; padding: 24px; border-radius: 0 0 8px 8px;">
            <table style="width: 100%; border-collapse: collapse;">
              <tr><td style="padding: 8px 0; font-weight: bold; color: #333; width: 100px;">Name:</td><td style="padding: 8px 0; color: #555;">${name}</td></tr>
              <tr><td style="padding: 8px 0; font-weight: bold; color: #333;">Email:</td><td style="padding: 8px 0;"><a href="mailto:${email}" style="color: #C9940A;">${email}</a></td></tr>
              <tr><td style="padding: 8px 0; font-weight: bold; color: #333;">Phone:</td><td style="padding: 8px 0; color: #555;">${phone || 'Not provided'}</td></tr>
              <tr><td style="padding: 8px 0; font-weight: bold; color: #333;">Subject:</td><td style="padding: 8px 0; color: #555;">${subject}</td></tr>
            </table>
            <div style="margin-top: 16px; padding: 16px; background: white; border-radius: 6px; border-left: 4px solid #C9940A;">
              <p style="font-weight: bold; color: #333; margin: 0 0 8px;">Message:</p>
              <p style="color: #555; margin: 0; white-space: pre-wrap;">${message}</p>
            </div>
            <p style="color: #999; font-size: 11px; margin-top: 16px;">Submitted at: ${new Date().toLocaleString('en-GB', { timeZone: 'Europe/London' })}</p>
          </div>
        </div>
      `;

      let senderEmail = 'noreply@tradethemarkets.co.uk';
      try {
        senderEmail = `noreply@${new URL(appUrl)?.hostname}`;
      } catch { /* ignore */ }

      await fetch('https://apps.abacus.ai/api/sendNotificationEmail', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          deployment_token: process.env.ABACUSAI_API_KEY,
          app_id: process.env.WEB_APP_ID,
          notification_id: process.env.NOTIF_ID_CONTACT_FORM_SUBMISSION,
          subject: `New Enquiry from ${name} — ${subject}`,
          body: htmlBody,
          is_html: true,
          recipient_email: 'info@TradeTheMarkets.co.uk',
          reply_to: email,
          sender_email: senderEmail,
          sender_alias: 'TradeTheMarkets',
        }),
      });
    } catch (emailErr: any) {
      console.error('Email notification error:', emailErr);
      // Don't fail the request if email fails
    }

    return NextResponse.json({ success: true, message: 'Message sent successfully!' });
  } catch (err: any) {
    console.error('Contact API error:', err);
    return NextResponse.json(
      { success: false, message: 'Failed to process your enquiry. Please try again.' },
      { status: 500 }
    );
  }
}
