import type { APIRoute } from 'astro';
import { supabase } from '../../../lib/supabase';
import { createClient } from '@supabase/supabase-js';

export const prerender = false;

export const GET: APIRoute = async ({ request, url }) => {
  const organizationId = url.searchParams.get('organization_id');
  const eventId = url.searchParams.get('event_id');
  
  if (!organizationId) {
    return new Response(JSON.stringify({ 
      success: false, 
      error: 'Organization ID is required' 
    }), { status: 400 });
  }

  // Authentication
  const authHeader = request.headers.get('authorization');
  if (!authHeader) {
    return new Response(JSON.stringify({ 
      success: false, 
      error: 'Authorization header required' 
    }), { status: 401 });
  }

  const token = authHeader.replace('Bearer ', '');
  const { data: { user }, error: authError } = await supabase.auth.getUser(token);

  if (authError || !user) {
    return new Response(JSON.stringify({ 
      success: false, 
      error: 'Invalid authentication token' 
    }), { status: 401 });
  }

  // Create authenticated Supabase client
  const authenticatedSupabase = createClient(
    import.meta.env.PUBLIC_SUPABASE_URL,
    import.meta.env.PUBLIC_SUPABASE_ANON_KEY,
    {
      global: {
        headers: {
          Authorization: `Bearer ${token}`
        }
      }
    }
  );

  try {
    console.log('GET /api/custom-pages - Parameters:', { organizationId, eventId });
    
    let query = authenticatedSupabase
      .from('custom_sales_pages')
      .select(`
        *,
        template:custom_page_templates(*),
        event:events(title, organizations(name))
      `)
      .eq('organization_id', organizationId)
      .order('updated_at', { ascending: false });

    if (eventId) {
      query = query.eq('event_id', eventId);
    }

    const { data: pages, error } = await query;

    console.log('Query result:', { pages: pages?.length || 0, error });

    if (error) {
      console.error('Supabase error fetching custom pages:', error);
      return new Response(JSON.stringify({ 
        success: false, 
        error: 'Failed to fetch custom pages',
        details: error.message 
      }), { status: 500 });
    }

    return new Response(JSON.stringify({ 
      success: true, 
      pages: pages || [] 
    }), { status: 200 });

  } catch (error) {
    console.error('Unexpected error in GET /api/custom-pages:', error);
    return new Response(JSON.stringify({ 
      success: false, 
      error: 'Internal server error',
      details: error instanceof Error ? error.message : 'Unknown error'
    }), { status: 500 });
  }
};

export const POST: APIRoute = async ({ request }) => {
  try {
    console.log('POST /api/custom-pages - Request received');
    console.log('Content-Type:', request.headers.get('content-type'));
    console.log('Authorization:', request.headers.get('authorization'));
    
    let body;
    try {
      body = await request.json();
      console.log('Request body:', body);
    } catch (jsonError) {
      console.error('JSON parsing error:', jsonError);
      return new Response(JSON.stringify({ 
        success: false, 
        error: 'Invalid JSON in request body' 
      }), { status: 400 });
    }
    const { 
      organization_id, 
      event_id, 
      template_id, 
      custom_slug, 
      meta_title, 
      meta_description, 
      created_by 
    } = body;
    
    console.log('Parsed values:', { organization_id, event_id, template_id, custom_slug, meta_title, meta_description, created_by });

    // Authentication
    const authHeader = request.headers.get('authorization');
    if (!authHeader) {
      return new Response(JSON.stringify({ 
        success: false, 
        error: 'Authorization header required' 
      }), { status: 401 });
    }

    const token = authHeader.replace('Bearer ', '');
    const { data: { user }, error: authError } = await supabase.auth.getUser(token);

    if (authError || !user) {
      return new Response(JSON.stringify({ 
        success: false, 
        error: 'Invalid authentication token' 
      }), { status: 401 });
    }

    console.log('Authenticated user:', user.id);

    // Create authenticated Supabase client
    const authenticatedSupabase = createClient(
      import.meta.env.PUBLIC_SUPABASE_URL,
      import.meta.env.PUBLIC_SUPABASE_ANON_KEY,
      {
        global: {
          headers: {
            Authorization: `Bearer ${token}`
          }
        }
      }
    );

    if (!organization_id || !event_id || !custom_slug) {
      return new Response(JSON.stringify({ 
        success: false, 
        error: 'Organization ID, Event ID, and custom slug are required' 
      }), { status: 400 });
    }

    // Get or create a default template if none provided
    let finalTemplateId = template_id;
    if (!finalTemplateId) {
      // Look for an existing default template for this organization
      const { data: defaultTemplate } = await authenticatedSupabase
        .from('custom_page_templates')
        .select('id')
        .eq('organization_id', organization_id)
        .eq('name', 'Default Template')
        .single();

      if (defaultTemplate) {
        finalTemplateId = defaultTemplate.id;
      } else {
        // Create a default template
        const { data: newTemplate, error: templateError } = await authenticatedSupabase
          .from('custom_page_templates')
          .insert({
            organization_id,
            name: 'Default Template',
            description: 'Basic template with essential elements',
            page_data: {
              sections: [
                { type: 'hero', title: 'Event Title', subtitle: 'Event Description' },
                { type: 'ticket-selector', title: 'Select Your Tickets' },
                { type: 'event-details', title: 'Event Details' }
              ]
            },
            created_by: user.id
          })
          .select('id')
          .single();

        if (templateError) {
          console.error('Error creating default template:', templateError);
          // Continue without template for now
        } else {
          finalTemplateId = newTemplate.id;
        }
      }
    }

    // Check if slug is already taken
    const { data: existing } = await authenticatedSupabase
      .from('custom_sales_pages')
      .select('id')
      .eq('custom_slug', custom_slug)
      .single();

    if (existing) {
      return new Response(JSON.stringify({ 
        success: false, 
        error: 'Custom slug is already taken' 
      }), { status: 409 });
    }

    const { data: page, error } = await authenticatedSupabase
      .from('custom_sales_pages')
      .insert({
        organization_id,
        event_id,
        template_id: finalTemplateId,
        custom_slug,
        meta_title,
        meta_description,
        created_by: user.id,
        is_active: true
      })
      .select()
      .single();

    if (error) {
      console.error('Supabase error creating custom page:', error);
      return new Response(JSON.stringify({ 
        success: false, 
        error: 'Failed to create custom page',
        details: error.message 
      }), { status: 500 });
    }

    return new Response(JSON.stringify({ 
      success: true, 
      page 
    }), { status: 201 });

  } catch (error) {
    console.error('Unexpected error in POST /api/custom-pages:', error);
    return new Response(JSON.stringify({ 
      success: false, 
      error: 'Internal server error',
      details: error instanceof Error ? error.message : 'Unknown error'
    }), { status: 500 });
  }
};