export const prerender = false;

import type { APIRoute } from 'astro';
import { supabase } from '../../../lib/supabase';
import { verifyAuth } from '../../../lib/auth';
import { sendApplicationReceivedEmail } from '../../../lib/email';

export const POST: APIRoute = async ({ request }) => {
  try {
    // Verify authentication
    const authContext = await verifyAuth(request);
    if (!authContext) {
      return new Response(JSON.stringify({ error: 'Unauthorized' }), { 
        status: 401,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    const { organization_id } = await request.json();

    if (!organization_id) {
      return new Response(JSON.stringify({ error: 'Organization ID required' }), { 
        status: 400,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    // Get organization and user data
    const { data: orgData, error: orgError } = await supabase
      .from('organizations')
      .select(`
        *,
        users!inner(id, email, name)
      `)
      .eq('id', organization_id)
      .eq('users.role', 'organizer')
      .single();

    if (orgError || !orgData) {
      return new Response(JSON.stringify({ error: 'Organization not found' }), { 
        status: 404,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    const user = orgData.users as any;

    // Send application received email
    await sendApplicationReceivedEmail({
      organizationName: orgData.name,
      userEmail: user.email,
      userName: user.name || user.email,
      expectedApprovalTime: '1-2 business days',
      referenceNumber: orgData.id.substring(0, 8).toUpperCase(),
      nextSteps: [
        'Our team will review your application and business information',
        'We may contact you for additional details if needed',
        'You\'ll receive an email notification once approved',
        'After approval, you can complete secure Stripe payment setup'
      ]
    });

    return new Response(JSON.stringify({ 
      success: true,
      message: 'Application received email sent successfully'
    }), {
      status: 200,
      headers: { 'Content-Type': 'application/json' }
    });

  } catch (error) {

    return new Response(JSON.stringify({ 
      error: 'Failed to send application received email',
      details: error instanceof Error ? error.message : 'Unknown error'
    }), { 
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
};