export const prerender = false;

import type { APIRoute } from 'astro';
import { supabase } from '../../../lib/supabase';
import Stripe from 'stripe';

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
  apiVersion: '2024-06-20',
});

export const GET: APIRoute = async ({ request, url }) => {
  try {
    // Get current user
    const { data: { user }, error: userError } = await supabase.auth.getUser();
    if (userError || !user) {
      return new Response(JSON.stringify({ error: 'Unauthorized' }), {
        status: 401,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    // Check if user is admin
    const { data: userRole } = await supabase
      .from('user_roles')
      .select('role')
      .eq('user_id', user.id)
      .eq('role', 'admin')
      .single();

    if (!userRole) {
      return new Response(JSON.stringify({ error: 'Admin access required' }), {
        status: 403,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    // Get query parameters
    const searchParams = url.searchParams;
    const page = parseInt(searchParams.get('page') || '1');
    const limit = parseInt(searchParams.get('limit') || '25');
    const status = searchParams.get('status');

    // Get organizations with their subscription info
    let query = supabase
      .from('organizations')
      .select(`
        *,
        users (
          id,
          email,
          name
        )
      `)
      .order('created_at', { ascending: false });

    // Apply pagination
    const offset = (page - 1) * limit;
    query = query.range(offset, offset + limit - 1);

    const { data: organizations, error: orgsError } = await query;

    if (orgsError) {
      throw orgsError;
    }

    // Get Stripe subscription info for each organization
    const organizationsWithSubscriptions = await Promise.all(
      organizations.map(async (org) => {
        let subscriptionInfo = null;
        
        if (org.stripe_account_id) {
          try {
            // Get Stripe account info
            const account = await stripe.accounts.retrieve(org.stripe_account_id);
            
            // Check if there are any subscriptions (this would be custom logic)
            // For now, we'll just return account status
            subscriptionInfo = {
              stripe_account_id: org.stripe_account_id,
              account_status: account.charges_enabled ? 'active' : 'inactive',
              details_submitted: account.details_submitted,
              payouts_enabled: account.payouts_enabled,
              country: account.country,
              created: account.created
            };
          } catch (stripeError) {
            console.error('Error fetching Stripe account:', stripeError);
            subscriptionInfo = {
              stripe_account_id: org.stripe_account_id,
              account_status: 'error',
              error: stripeError.message
            };
          }
        }

        return {
          ...org,
          subscription: subscriptionInfo
        };
      })
    );

    // Filter by status if provided
    const filteredOrgs = status 
      ? organizationsWithSubscriptions.filter(org => 
          org.subscription?.account_status === status
        )
      : organizationsWithSubscriptions;

    // Get total count
    const { count, error: countError } = await supabase
      .from('organizations')
      .select('*', { count: 'exact', head: true });

    if (countError) {
      throw countError;
    }

    return new Response(JSON.stringify({
      organizations: filteredOrgs,
      pagination: {
        page,
        limit,
        total: count || 0,
        pages: Math.ceil((count || 0) / limit)
      }
    }), {
      status: 200,
      headers: { 'Content-Type': 'application/json' }
    });

  } catch (error) {
    console.error('Error fetching subscriptions:', error);
    return new Response(JSON.stringify({ 
      error: 'Failed to fetch subscriptions',
      details: error.message 
    }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
};

export const POST: APIRoute = async ({ request }) => {
  try {
    const body = await request.json();
    const { action, organization_id, ...data } = body;

    // Get current user
    const { data: { user }, error: userError } = await supabase.auth.getUser();
    if (userError || !user) {
      return new Response(JSON.stringify({ error: 'Unauthorized' }), {
        status: 401,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    // Check if user is admin
    const { data: userRole } = await supabase
      .from('user_roles')
      .select('role')
      .eq('user_id', user.id)
      .eq('role', 'admin')
      .single();

    if (!userRole) {
      return new Response(JSON.stringify({ error: 'Admin access required' }), {
        status: 403,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    // Get organization
    const { data: organization, error: orgError } = await supabase
      .from('organizations')
      .select('*')
      .eq('id', organization_id)
      .single();

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

    let result;
    
    switch (action) {
      case 'suspend_account':
        if (organization.stripe_account_id) {
          try {
            // In a real scenario, you'd implement custom suspension logic
            // For now, we'll just update our database
            result = await supabase
              .from('organizations')
              .update({ 
                status: 'suspended',
                suspended_at: new Date().toISOString(),
                suspended_by: user.id
              })
              .eq('id', organization_id)
              .select()
              .single();
          } catch (error) {
            throw new Error('Failed to suspend account');
          }
        }
        break;
        
      case 'reactivate_account':
        result = await supabase
          .from('organizations')
          .update({ 
            status: 'active',
            suspended_at: null,
            suspended_by: null
          })
          .eq('id', organization_id)
          .select()
          .single();
        break;
        
      case 'update_billing':
        // This would typically involve updating Stripe subscription
        // For now, just update organization metadata
        result = await supabase
          .from('organizations')
          .update(data)
          .eq('id', organization_id)
          .select()
          .single();
        break;
        
      default:
        return new Response(JSON.stringify({ error: 'Invalid action' }), {
          status: 400,
          headers: { 'Content-Type': 'application/json' }
        });
    }

    if (result && result.error) {
      throw result.error;
    }

    return new Response(JSON.stringify({
      success: true,
      organization: result?.data || { message: 'Action completed' }
    }), {
      status: 200,
      headers: { 'Content-Type': 'application/json' }
    });

  } catch (error) {
    console.error('Error managing subscription:', error);
    return new Response(JSON.stringify({ 
      error: 'Failed to manage subscription',
      details: error.message 
    }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
};