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 { sendRejectionNotificationEmail } 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, rejection_reason } = await request.json();

    if (!organization_id || !rejection_reason) {
      return new Response(JSON.stringify({ error: 'Organization ID and rejection reason are 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 pending approval
    if (orgData.account_status !== 'pending_approval') {
      return new Response(JSON.stringify({ error: 'Organization is not pending approval' }), { 
        status: 400,
        headers: { 'Content-Type': 'application/json' }
      });
    }

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

    if (updateError) {

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

    // Log the rejection
    const { error: auditError } = await supabase
      .from('approval_audit_log')
      .insert({
        organization_id,
        action: 'rejected',
        actor_id: user.id,
        reason: rejection_reason,
        previous_status: 'pending_approval',
        new_status: 'rejected',
        metadata: {
          rejection_reason,
          approval_score: orgData.approval_score
        }
      });

    if (auditError) {

    }

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

    // Send rejection notification email
    try {
      // Create a rejection email function if it doesn't exist
      const emailData = {
        organizationName: orgData.name,
        userEmail: (orgData.users as any).email,
        userName: (orgData.users as any).name || (orgData.users as any).email,
        rejectionReason: rejection_reason,
        supportEmail: 'support@blackcanyontickets.com',
        reapplyUrl: `${new URL(request.url).origin}/onboarding/organization`
      };

      // For now, send a basic rejection email using the existing email system
      const { error: emailError } = await supabase.functions.invoke('send-rejection-email', {
        body: emailData
      });

      if (emailError) {

      }
    } catch (emailError) {

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

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

  } catch (error) {

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