export const prerender = false;

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

export const POST: APIRoute = async ({ request }) => {
  try {
    // Verify authentication and admin role
    const authContext = await verifyAuth(request);
    if (!authContext || !authContext.isAdmin) {
      return new Response(JSON.stringify({ error: 'Admin access required' }), { 
        status: 403,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    const { user } = authContext;
    const { organization_id, welcome_message } = 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' }
      });
    }

    // Check if organization is already approved
    if (orgData.account_status === 'approved' || orgData.account_status === 'active') {
      return new Response(JSON.stringify({ error: 'Organization is already approved' }), { 
        status: 400,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    // Update organization status
    const { error: updateError } = await supabase
      .from('organizations')
      .update({
        account_status: 'approved',
        approved_at: new Date().toISOString(),
        approved_by: user.id,
        approval_reason: 'Manually approved by admin'
      })
      .eq('id', organization_id);

    if (updateError) {

      return new Response(JSON.stringify({ error: 'Failed to approve organization' }), { 
        status: 500,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    // Log the approval
    const { error: auditError } = await supabase
      .from('approval_audit_log')
      .insert({
        organization_id,
        action: 'manually_approved',
        actor_id: user.id,
        reason: 'Manually approved by admin',
        previous_status: 'pending_approval',
        new_status: 'approved',
        metadata: {
          welcome_message: welcome_message || null,
          approval_score: orgData.approval_score
        }
      });

    if (auditError) {

    }

    // Log user activity
    await logUserActivity({
      userId: user.id,
      action: 'organization_approved',
      resourceType: 'organization',
      resourceId: organization_id,
      details: {
        organization_name: orgData.name,
        owner_email: (orgData.users as any).email,
        approval_score: orgData.approval_score,
        welcome_message: welcome_message || null
      }
    });

    // Send approval notification email
    try {
      await sendApprovalNotificationEmail({
        organizationName: orgData.name,
        userEmail: (orgData.users as any).email,
        userName: (orgData.users as any).name || (orgData.users as any).email,
        approvedBy: user.name || user.email || 'Admin',
        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: welcome_message || undefined
      });
    } catch (emailError) {

      // Don't fail the request for email errors
    }

    return new Response(JSON.stringify({
      success: true,
      message: 'Organization approved successfully',
      organization_id
    }), {
      status: 200,
      headers: { 'Content-Type': 'application/json' }
    });

  } catch (error) {

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