import { getToken } from "next-auth/jwt";
import { AdmissionRequestTemplate } from "../../../../lib/mailer";

export async function POST(req) {
  try {
    // Try to get token but don't fail hard if NEXTAUTH_SECRET is missing
    let token = null;
    try {
      if (process.env.NEXTAUTH_SECRET) {
        token = await getToken({ req, secret: process.env.NEXTAUTH_SECRET });
      } else {
        token = await getToken({ req });
      }
    } catch (authError) {
      console.warn('Auth token retrieval failed:', authError?.message || authError);
      token = null;
    }

    const body = await req.json().catch(() => ({}));
    const { item, userInfo: bodyUserInfo } = body || {};
    
    if (!item) {
      return Response.json({ 
        success: false, 
        error: 'Missing item payload' 
      }, { status: 400 });
    }

    // If token exists, enforce role restriction; otherwise allow as guest
    if (token && !['student', 'consultant'].includes(token.role)) {
      return Response.json({ 
        success: false, 
        error: 'Unauthorized' 
      }, { status: 401 });
    }

    const userInfo = token ? {
      name: token.name || 'Unknown User',
      phone: token.phone || 'Not provided',
      email: token.email || 'No email',
    } : (bodyUserInfo || {
      name: 'Guest User',
      phone: body?.phone || 'Not provided',
      email: body?.email || 'No email',
    });

    console.log('📧 Processing admission request:', {
      itemType: item.name ? 'University' : 'Course',
      itemName: item.name || item.title,
      userInfo: { name: userInfo.name, email: userInfo.email },
      hasToken: !!token
    });

    // Determine item type and extract university information
    let itemType = 'Item';
    let universityEmail = null;
    let universityName = 'Unknown University';
    
    if (item.university_id || item.university_info || item.university_alternate_email || item.university_name) {
      itemType = 'Course';
      universityName = item.university_name || item.university || 'Unknown University';
      universityEmail = item.university_alternate_email || item.university_info?.alternate_email || item.alternate_email;
    } else if (item.name && (item.logo || item.banner_image || item.type === 'university' || item.alternate_email)) {
      itemType = 'University';
      universityName = item.name || 'Unknown University';
      universityEmail = item.alternate_email || item.email || item.contact?.email;
    } else if (item.title && item.guide_type) {
      itemType = 'Guide';
    } else if (item.title) {
      itemType = 'Article';
    }

    const itemName = item.name || item.title || 'Unknown';
    const itemLocation = item.location || item.city || item.country || item.university_name || '';

    console.log('🔍 Extracted university details:', { 
      universityName, 
      universityEmail, 
      itemType, 
      itemName,
      hasAlternateEmail: !!item.alternate_email,
      alternateEmail: item.alternate_email
    });

    let success = false;
    let fallbackUsed = false;
    let finalEmail = universityEmail;
    let errorDetails = null;
    let messageId = null;
    
    // Email priority: 1. item.alternate_email, 2. other university emails, 3. fallback
    if (item.alternate_email) {
      console.log('✅ Using item.alternate_email as primary:', item.alternate_email);
      finalEmail = item.alternate_email;
    } else if (!universityEmail) {
      console.warn('❌ No university email found, using fallback to info@universitiespage.com');
      finalEmail = "info@universitiespage.com";
      fallbackUsed = true;
    }

    console.log('🎯 Final email destination:', finalEmail);

    try {
      const result = await AdmissionRequestTemplate({
        to: finalEmail,
        itemType,
        universityName,
        itemName,
        itemLocation,
        userInfo,
        isFallback: fallbackUsed,
        originalUniversityName: fallbackUsed ? universityName : undefined
      });

      success = !!result.messageId;
      messageId = result.messageId;
      
      console.log('✅ Email sent successfully:', { 
        to: finalEmail, 
        messageId: result.messageId,
        fallbackUsed,
        accepted: result.accepted,
        rejected: result.rejected
      });

    } catch (error) {
      console.error('❌ Primary email sending failed:', error);
      errorDetails = error.message;
      
      // Log detailed error information
      console.error('🔍 Error analysis:', {
        message: error.message,
        stack: error.stack,
        finalEmail,
        fallbackUsed
      });

      // If primary email fails and we haven't already used fallback, try fallback
      if (!fallbackUsed) {
        console.warn('🔄 Primary email failed, attempting fallback to info@universitiespage.com');
        
        try {
          const fallbackResult = await AdmissionRequestTemplate({
            to: "info@universitiespage.com",
            itemType,
            universityName,
            itemName,
            itemLocation,
            userInfo,
            isFallback: true,
            originalUniversityName: universityName,
            fallbackReason: `Primary email ${finalEmail} failed: ${error.message}`
          });

          success = !!fallbackResult.messageId;
          messageId = fallbackResult.messageId;
          fallbackUsed = true;
          finalEmail = "info@universitiespage.com";
          
          console.log('✅ Fallback email sent successfully:', { 
            messageId: fallbackResult.messageId,
            accepted: fallbackResult.accepted 
          });

        } catch (fallbackError) {
          console.error('❌ Fallback email also failed:', fallbackError);
          success = false;
          errorDetails = `Primary: ${error.message}, Fallback: ${fallbackError.message}`;
        }
      } else {
        success = false;
      }
    }

    const responseMessage = success 
      ? (fallbackUsed 
          ? 'Request forwarded to support team (university email not available)' 
          : 'Request sent successfully to university')
      : 'Failed to process request';

    return Response.json({ 
      success,
      fallbackUsed,
      emailUsed: finalEmail,
      messageId,
      error: errorDetails,
      message: responseMessage
    });

  } catch (error) {
    console.error("❌ API Error in /api/request-info:", error);
    
    return Response.json({ 
      success: false, 
      error: 'Internal server error',
      details: process.env.NODE_ENV === 'development' ? error.message : undefined
    }, { status: 500 });
  }
}