export const prerender = false;

import type { APIRoute } from 'astro';
import { supabase } from '../../../lib/supabase';
import { verifyAuth } from '../../../lib/auth';
import { sendAdminNotificationEmail } 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 { id: string; email: string; name: string | null };

    // Check if organization should be auto-approved
    const { data: shouldAutoApprove, error: approvalError } = await supabase
      .rpc('should_auto_approve', { org_id: organization_id });

    if (approvalError) {
      // Log error but continue with notification
      console.warn('Failed to check auto-approval status:', approvalError);
    }

    // Send admin notification email
    await sendAdminNotificationEmail({
      organizationName: orgData.name,
      userEmail: user.email,
      userName: user.name || user.email,
      businessType: orgData.business_type || 'Not specified',
      approvalScore: orgData.approval_score || 0,
      requiresReview: !shouldAutoApprove,
      adminDashboardUrl: `${new URL(request.url).origin}/admin/pending-approvals`
    });

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

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