export const prerender = false;

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

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') || '50');
    const status = searchParams.get('status');
    const eventId = searchParams.get('event_id');
    const email = searchParams.get('email');
    const refundStatus = searchParams.get('refund_status');

    // Build query
    let query = supabase
      .from('tickets')
      .select(`
        *,
        events (
          id,
          title,
          venue,
          start_time,
          organizations (
            id,
            name
          )
        ),
        ticket_types (
          id,
          name,
          price
        ),
        purchase_attempts (
          id,
          total_amount,
          purchaser_email,
          purchaser_name,
          status,
          created_at
        )
      `)
      .order('created_at', { ascending: false });

    // Apply filters
    if (status) {
      query = query.eq('checked_in', status === 'checked_in');
    }
    if (eventId) {
      query = query.eq('event_id', eventId);
    }
    if (email) {
      query = query.ilike('purchaser_email', `%${email}%`);
    }
    if (refundStatus) {
      query = query.eq('refund_status', refundStatus);
    }

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

    const { data: tickets, error: ticketsError } = await query;

    if (ticketsError) {
      throw ticketsError;
    }

    // Get total count for pagination
    let countQuery = supabase
      .from('tickets')
      .select('*', { count: 'exact', head: true });

    if (status) {
      countQuery = countQuery.eq('checked_in', status === 'checked_in');
    }
    if (eventId) {
      countQuery = countQuery.eq('event_id', eventId);
    }
    if (email) {
      countQuery = countQuery.ilike('purchaser_email', `%${email}%`);
    }
    if (refundStatus) {
      countQuery = countQuery.eq('refund_status', refundStatus);
    }

    const { count, error: countError } = await countQuery;

    if (countError) {
      throw countError;
    }

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

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

export const POST: APIRoute = async ({ request }) => {
  try {
    const body = await request.json();
    const { action, ticket_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' }
      });
    }

    let result;
    
    switch (action) {
      case 'update_ticket': {
        result = await supabase
          .from('tickets')
          .update(data)
          .eq('id', ticket_id)
          .select()
          .single();
        break;
      }
        
      case 'check_in': {
        result = await supabase
          .from('tickets')
          .update({ 
            checked_in: true, 
            scanned_at: new Date().toISOString() 
          })
          .eq('id', ticket_id)
          .select()
          .single();
        break;
      }
        
      case 'cancel_ticket': {
        result = await supabase
          .from('tickets')
          .update({ 
            refund_status: 'cancelled',
            refund_requested_at: new Date().toISOString(),
            refund_reason: 'Admin cancelled',
            refunded_by: user.id
          })
          .eq('id', ticket_id)
          .select()
          .single();
        break;
      }
        
      default: {
        return new Response(JSON.stringify({ error: 'Invalid action' }), {
          status: 400,
          headers: { 'Content-Type': 'application/json' }
        });
      }
    }

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

    return new Response(JSON.stringify({
      success: true,
      ticket: result.data
    }), {
      status: 200,
      headers: { 'Content-Type': 'application/json' }
    });

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