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

export const prerender = false;

export const GET: APIRoute = async ({ request, url }) => {
  const organizationId = url.searchParams.get('organization_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 { data: { user }, error: authError } = await supabase.auth.getUser(
    authHeader.replace('Bearer ', '')
  );

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

  try {
    const { data: templates, error } = await supabase
      .from('custom_page_templates')
      .select('*')
      .eq('organization_id', organizationId)
      .eq('is_active', true)
      .order('updated_at', { ascending: false });

    if (error) {

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

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

  } catch (error) {

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

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

    if (!name || !organization_id) {
      return new Response(JSON.stringify({ 
        success: false, 
        error: 'Name and organization ID are required' 
      }), { status: 400 });
    }

    const { data: template, error } = await supabase
      .from('custom_page_templates')
      .insert({
        name,
        description,
        organization_id,
        created_by,
        page_data: {},
        is_active: true
      })
      .select()
      .single();

    if (error) {

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

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

  } catch (error) {

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