import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/db';
import { BRAND } from '@/lib/white-label/constants';
import { z } from 'zod';

export const dynamic = 'force-dynamic';

const designPartnerSchema = z.object({
  companyName: z.string().min(1, 'Company name is required').max(200),
  contactName: z.string().min(1, 'Contact name is required').max(200),
  email: z.string().email('Valid email is required').max(255),
  companySize: z.string().min(1, 'Company size is required').max(100),
  useCase: z.string().min(1, 'Use case is required').max(2000),
});

export async function POST(request: NextRequest) {
  try {
    const body = await request.json().catch(() => null);
    if (!body) {
      return NextResponse.json(
        { error: 'Invalid JSON body' },
        { status: 400 }
      );
    }

    const parsed = designPartnerSchema.safeParse(body);
    if (!parsed.success) {
      return NextResponse.json(
        { error: parsed.error.issues[0]?.message || 'Invalid input' },
        { status: 400 }
      );
    }

    const { companyName, contactName, email, companySize, useCase } = parsed.data;

    const submission = await prisma.designPartnerSubmission.create({
      data: {
        companyName,
        contactName,
        email,
        companySize,
        useCase,
      },
    });

    // Send email notification to admin
    try {
      const appUrl = process.env.NEXTAUTH_URL || '';
      const htmlBody = `
        <div style="font-family: 'Segoe UI', Arial, sans-serif; max-width: 640px; margin: 0 auto; background: #0C1222; color: #e2e8f0; padding: 32px; border-radius: 12px;">
          <div style="text-align: center; margin-bottom: 24px;">
            <h1 style="color: #0EA5E9; font-size: 22px; margin: 0;">👻 New Design Partner Application</h1>
            <p style="color: #64748b; font-size: 13px; margin-top: 6px;">{BRAND.companyName}</p>
          </div>
          <div style="background: rgba(15,23,42,0.8); border: 1px solid rgba(6,182,212,0.2); border-radius: 10px; padding: 24px; margin-bottom: 20px;">
            <table style="width: 100%; border-collapse: collapse;">
              <tr><td style="padding: 8px 0; color: #64748b; width: 130px;">Company</td><td style="padding: 8px 0; color: #f1f5f9; font-weight: 600;">${companyName}</td></tr>
              <tr><td style="padding: 8px 0; color: #64748b;">Contact</td><td style="padding: 8px 0; color: #f1f5f9; font-weight: 600;">${contactName}</td></tr>
              <tr><td style="padding: 8px 0; color: #64748b;">Email</td><td style="padding: 8px 0;"><a href="mailto:${email}" style="color: #0EA5E9;">${email}</a></td></tr>
              <tr><td style="padding: 8px 0; color: #64748b;">Company Size</td><td style="padding: 8px 0; color: #f1f5f9;">${companySize}</td></tr>
              <tr><td style="padding: 8px 0; color: #64748b;">Use Case</td><td style="padding: 8px 0; color: #f1f5f9;">${useCase}</td></tr>
            </table>
          </div>
          <p style="color: #475569; font-size: 12px; text-align: center;">Submitted ${new Date().toLocaleString('en-US', { timeZone: 'America/Chicago' })} CT</p>
        </div>
      `;

      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_DESIGN_PARTNER_APPLICATION,
          subject: `New Design Partner: ${companyName} (${contactName})`,
          body: htmlBody,
          is_html: true,
          recipient_email: 'ghostfoundrysyndicate@outlook.com',
          sender_alias: BRAND.companyName,
        }),
      });
    } catch (emailError) {
      console.error('Email notification failed (non-blocking):', emailError);
    }

    return NextResponse.json({ success: true, id: submission.id });
  } catch (error) {
    console.error('Design partner submission error:', error);
    return NextResponse.json(
      { error: 'Failed to submit application' },
      { status: 500 }
    );
  }
}
