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 ({ params, request }) => {
  const { id } = params;

  if (!id) {
    return new Response(JSON.stringify({ 
      success: false, 
      error: 'Page 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 {
    const { data: page, error } = await authenticatedSupabase
      .from('custom_sales_pages')
      .select(`
        *,
        template:custom_page_templates(*),
        event:events(title, organizations(name))
      `)
      .eq('id', id)
      .single();

    if (error) {

      return new Response(JSON.stringify({ 
        success: false, 
        error: 'Page not found' 
      }), { status: 404 });
    }

    return new Response(JSON.stringify({ 
      success: true, 
      page,
      pageData: page.page_data || page.template?.page_data || {}
    }), { status: 200 });

  } catch (error) {

    return new Response(JSON.stringify({ 
      success: false, 
      error: 'Internal server error' 
    }), { status: 500 });
  }
};

export const PUT: APIRoute = async ({ params, request }) => {
  const { id } = params;

  if (!id) {
    return new Response(JSON.stringify({ 
      success: false, 
      error: 'Page 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 {
    const body = await request.json();
    const { 
      custom_slug, 
      meta_title, 
      meta_description, 
      page_data, 
      custom_css, 
      is_active, 
      is_default,
      updated_by 
    } = body;

    const updateData: any = { 
      updated_at: new Date().toISOString() 
    };

    if (custom_slug !== undefined) updateData.custom_slug = custom_slug;
    if (meta_title !== undefined) updateData.meta_title = meta_title;
    if (meta_description !== undefined) updateData.meta_description = meta_description;
    if (page_data !== undefined) updateData.page_data = page_data;
    if (custom_css !== undefined) updateData.custom_css = custom_css;
    if (is_active !== undefined) updateData.is_active = is_active;
    if (is_default !== undefined) updateData.is_default = is_default;
    if (updated_by) updateData.updated_by = updated_by;

    const { data: page, error } = await authenticatedSupabase
      .from('custom_sales_pages')
      .update(updateData)
      .eq('id', id)
      .select()
      .single();

    if (error) {

      return new Response(JSON.stringify({ 
        success: false, 
        error: 'Failed to update page' 
      }), { status: 500 });
    }

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

  } catch (error) {

    return new Response(JSON.stringify({ 
      success: false, 
      error: 'Internal server error' 
    }), { status: 500 });
  }
};

export const DELETE: APIRoute = async ({ params, request }) => {
  const { id } = params;

  if (!id) {
    return new Response(JSON.stringify({ 
      success: false, 
      error: 'Page 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 {
    const { error } = await authenticatedSupabase
      .from('custom_sales_pages')
      .delete()
      .eq('id', id);

    if (error) {

      return new Response(JSON.stringify({ 
        success: false, 
        error: 'Failed to delete page' 
      }), { status: 500 });
    }

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

  } catch (error) {

    return new Response(JSON.stringify({ 
      success: false, 
      error: 'Internal server error' 
    }), { status: 500 });
  }
};