import type { APIRoute } from 'astro';
import { territoryManagerAPI } from '../../../lib/territory-manager-api';
import type { ApplicationFormData } from '../../../lib/territory-manager-types';

export const POST: APIRoute = async ({ request }) => {
  try {
    const formData = await request.formData();
    
    // Extract form data
    const applicationData: ApplicationFormData = {
      personalInfo: {
        fullName: formData.get('fullName') as string,
        email: formData.get('email') as string,
        phone: formData.get('phone') as string,
        address: {
          street: formData.get('street') as string,
          city: formData.get('city') as string,
          state: formData.get('state') as string,
          zip_code: formData.get('zip') as string,
          country: 'US'
        }
      },
      preferences: {
        desiredTerritory: formData.get('desiredTerritory') as string,
        hasTransportation: formData.get('hasTransportation') === 'yes',
        hasEventExperience: formData.get('hasExperience') === 'yes',
        motivation: formData.get('motivation') as string,
        availability: {
          days_of_week: JSON.parse(formData.get('daysAvailable') as string || '[]'),
          time_ranges: [], // Default empty, can be expanded later
          travel_radius: 50 // Default 50 miles
        }
      },
      documents: {
        // Files would be uploaded to storage separately
        // For now, we'll just store the file names
      },
      consent: {
        background_check: formData.get('consentBackground') === 'true',
        data_processing: formData.get('consentData') === 'true',
        terms_of_service: formData.get('consentTerms') === 'true',
        privacy_policy: formData.get('consentData') === 'true'
      }
    };

    // Validate required fields
    if (!applicationData.personalInfo.fullName || 
        !applicationData.personalInfo.email || 
        !applicationData.personalInfo.phone ||
        !applicationData.preferences.desiredTerritory ||
        !applicationData.preferences.motivation) {
      return new Response(JSON.stringify({ error: 'Missing required fields' }), {
        status: 400,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    // Validate consent checkboxes
    if (!applicationData.consent.background_check || 
        !applicationData.consent.data_processing || 
        !applicationData.consent.terms_of_service) {
      return new Response(JSON.stringify({ error: 'Required consent not provided' }), {
        status: 400,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    // Handle file uploads
    const idUpload = formData.get('idUpload') as File;
    const resumeUpload = formData.get('resumeUpload') as File;

    if (idUpload) {
      // TODO: Upload to secure storage (AWS S3, Supabase Storage, etc.)
      // For now, we'll just validate file type and size
      const allowedTypes = ['image/jpeg', 'image/png', 'application/pdf'];
      if (!allowedTypes.includes(idUpload.type)) {
        return new Response(JSON.stringify({ error: 'Invalid ID file type' }), {
          status: 400,
          headers: { 'Content-Type': 'application/json' }
        });
      }
      
      if (idUpload.size > 10 * 1024 * 1024) { // 10MB limit
        return new Response(JSON.stringify({ error: 'ID file too large' }), {
          status: 400,
          headers: { 'Content-Type': 'application/json' }
        });
      }
    }

    if (resumeUpload) {
      const allowedTypes = ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'];
      if (!allowedTypes.includes(resumeUpload.type)) {
        return new Response(JSON.stringify({ error: 'Invalid resume file type' }), {
          status: 400,
          headers: { 'Content-Type': 'application/json' }
        });
      }
      
      if (resumeUpload.size > 10 * 1024 * 1024) { // 10MB limit
        return new Response(JSON.stringify({ error: 'Resume file too large' }), {
          status: 400,
          headers: { 'Content-Type': 'application/json' }
        });
      }
    }

    // Submit application
    const application = await territoryManagerAPI.submitApplication(applicationData);

    // Send confirmation email (would integrate with email service)
    await sendConfirmationEmail(applicationData.personalInfo.email, applicationData.personalInfo.fullName);

    // Log application submission for admin review
    console.log('Territory manager application submitted:', { applicationId: application.id, email: applicationData.personalInfo.email });

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

  } catch (error) {
    // Log error for debugging
    console.error('Failed to process territory manager application:', error);
    return new Response(JSON.stringify({ error: 'Internal server error' }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
};

async function sendConfirmationEmail(email: string, name: string) {
  // TODO: Integrate with email service (Resend, SendGrid, etc.)
  // For now, just log the action
  console.log('Sending confirmation email to:', email);

  // Example email content:
  const emailContent = {
    to: email,
    subject: 'Territory Manager Application Received - Black Canyon Tickets',
    html: `
      <h2>Thank you for your interest in becoming a Territory Manager!</h2>
      <p>Hi ${name},</p>
      <p>We've received your Territory Manager application and will review it within 2-3 business days.</p>
      <p>If your application is approved, you'll receive an email with next steps including:</p>
      <ul>
        <li>Background check process</li>
        <li>Access to your Territory Manager portal</li>
        <li>Training materials and resources</li>
        <li>Your exclusive territory assignment</li>
      </ul>
      <p>We're excited about the possibility of having you join our team!</p>
      <p>Best regards,<br>The Black Canyon Tickets Team</p>
    `
  };
  
  // TODO: Actually send the email
  return Promise.resolve();
}