export const prerender = false;

import type { APIRoute } from 'astro';
import { supabase } from '../../../lib/supabase';
import { verifyAuth } from '../../../lib/auth';
import { sendApprovalNotificationEmail } 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, auto_approved = false } = 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;

    // Get approver info
    let approvedBy = 'Auto-approved';
    if (!auto_approved && orgData.approved_by) {
      const { data: approver } = await supabase
        .from('users')
        .select('name, email')
        .eq('id', orgData.approved_by)
        .single();
      
      if (approver) {
        approvedBy = approver.name || approver.email;
      }
    }

    // Send approval notification email
    await sendApprovalNotificationEmail({
      organizationName: orgData.name,
      userEmail: user.email,
      userName: user.name || user.email,
      approvedBy,
      stripeOnboardingUrl: `${new URL(request.url).origin}/onboarding/stripe`,
      nextSteps: [
        'Complete secure Stripe Connect verification',
        'Provide bank account details for automated payouts',
        'Review and accept terms of service',
        'Your account will be activated immediately after completion'
      ],
      welcomeMessage: auto_approved 
        ? 'Your application met our auto-approval criteria - welcome to the platform!'
        : undefined
    });

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

  } catch (error) {

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