import type { APIRoute } from 'astro';
import { createSupabaseServerClient } from '../../../lib/supabase-ssr';
import { createSupabaseAdmin } from '../../../lib/supabase-admin';

export const GET: APIRoute = async ({ request, cookies }) => {
  try {
    // Check authentication
    const supabase = createSupabaseServerClient(cookies);
    const { data: { session }, error: sessionError } = await supabase.auth.getSession();
    
    if (sessionError || !session) {
      return new Response(JSON.stringify({ 
        success: false, 
        error: 'Authentication required' 
      }), { 
        status: 401,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    // Use admin client to bypass RLS
    const serviceClient = createSupabaseAdmin();
    
    // Get recent activity data
    const [eventsResult, ticketsResult, usersResult] = await Promise.all([
      serviceClient.from('events').select('*, organizations(name)').order('created_at', { ascending: false }).limit(5),
      serviceClient.from('tickets').select('*, events(title)').order('created_at', { ascending: false }).limit(10),
      serviceClient.from('users').select('*, organizations(name)').order('created_at', { ascending: false }).limit(5)
    ]);

    const activities = [];

    // Add recent events
    if (eventsResult.data) {
      eventsResult.data.forEach(event => {
        activities.push({
          type: 'event',
          title: `New event created: ${event.title}`,
          subtitle: `by ${event.organizations?.name || 'Unknown'}`,
          time: new Date(event.created_at),
          icon: '📅'
        });
      });
    }

    // Add recent users
    if (usersResult.data) {
      usersResult.data.forEach(user => {
        activities.push({
          type: 'user',
          title: `New user registered: ${user.name || user.email}`,
          subtitle: `Organization: ${user.organizations?.name || 'None'}`,
          time: new Date(user.created_at),
          icon: '👤'
        });
      });
    }

    // Add recent tickets
    if (ticketsResult.data) {
      ticketsResult.data.slice(0, 5).forEach(ticket => {
        activities.push({
          type: 'ticket',
          title: `Ticket sold: $${ticket.price}`,
          subtitle: `for ${ticket.events?.title || 'Unknown Event'}`,
          time: new Date(ticket.created_at),
          icon: '🎫'
        });
      });
    }

    // Sort by time and take the most recent 10
    activities.sort((a, b) => b.time - a.time);
    const recentActivities = activities.slice(0, 10);

    return new Response(JSON.stringify({
      success: true,
      data: recentActivities
    }), {
      status: 200,
      headers: { 'Content-Type': 'application/json' }
    });
  } catch (error) {
    console.error('Admin activity error:', error);
    return new Response(JSON.stringify({
      success: false,
      error: 'Failed to load recent activity'
    }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
};