import { NextRequest, NextResponse } from 'next/server';
import { getStripe } from '@/lib/stripe';
import { getServiceClient } from '@/lib/supabase';
import { getCurrencyForCountry, APPLICATION_AMOUNT } from '@/lib/countries';

interface ApplicationBody {
  firstName: string;
  lastName: string;
  email: string;
  phone: string;
  countryOfOrigin: string;
  dateOfBirth: string;
  educationLevel: string;
  yearsExperience: number;
  skills: string;
  cvUrl: string;
  targetCountry: string;
  jobSector: string;
  locale: string;
}

export async function POST(req: NextRequest) {
  try {
    const body: ApplicationBody = await req.json();

    const {
      firstName,
      lastName,
      email,
      phone,
      countryOfOrigin,
      dateOfBirth,
      educationLevel,
      yearsExperience,
      skills,
      cvUrl,
      targetCountry,
      jobSector,
      locale,
    } = body;

    const supabase = getServiceClient();

    // 1. Insert application into Supabase with pending payment status
    const { data: application, error: insertError } = await supabase
      .from('applications')
      .insert({
        first_name: firstName,
        last_name: lastName,
        email,
        phone,
        country_of_origin: countryOfOrigin,
        date_of_birth: dateOfBirth,
        education_level: educationLevel,
        years_experience: yearsExperience,
        skills,
        cv_url: cvUrl,
        target_country: targetCountry,
        job_sector: jobSector,
        payment_status: 'pending',
      })
      .select()
      .single();

    if (insertError || !application) {
      console.error('Supabase insert error:', insertError);
      return NextResponse.json(
        { error: 'Failed to create application' },
        { status: 500 }
      );
    }

    // 2. Get the correct currency for the target country
    const currency = getCurrencyForCountry(targetCountry);

    // 3. Create Stripe Checkout session
    const baseUrl = process.env.NEXT_PUBLIC_BASE_URL!;

    const session = await getStripe().checkout.sessions.create({
      mode: 'payment',
      line_items: [
        {
          price_data: {
            currency,
            unit_amount: APPLICATION_AMOUNT,
            product_data: {
              name: 'WorkBetter Job Application Fee',
            },
          },
          quantity: 1,
        },
      ],
      success_url: `${baseUrl}/${locale}/success?session_id={CHECKOUT_SESSION_ID}`,
      cancel_url: `${baseUrl}/${locale}/cancel`,
      customer_email: email,
      metadata: {
        application_id: application.id,
      },
    });

    // 4. Update application with stripe_session_id
    const { error: updateError } = await supabase
      .from('applications')
      .update({ stripe_session_id: session.id })
      .eq('id', application.id);

    if (updateError) {
      console.error('Supabase update error:', updateError);
    }

    // 5. Return checkout URL
    return NextResponse.json({ url: session.url });
  } catch (error) {
    console.error('Create checkout error:', error);
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    );
  }
}
