import type { APIRoute } from 'astro';
import { supabase, supabaseAdmin } from '../../../../lib/supabase';
import { getTokenFromHeader, verifyToken } from '../../../../lib/auth';

export const GET: APIRoute = async ({ url }) => {
  try {
    const page = parseInt(url.searchParams.get('page') || '1');
    const limit = Math.min(parseInt(url.searchParams.get('limit') || '20'), 100);
    const categorySlug = url.searchParams.get('category');
    const vendorSlug = url.searchParams.get('vendor');
    const search = url.searchParams.get('search');
    const featured = url.searchParams.get('featured') === 'true';
    const sort = url.searchParams.get('sort') || 'created_at';
    const order = url.searchParams.get('order') || 'desc';
    
    const from = (page - 1) * limit;
    const to = page * limit - 1;
    
    let query = supabase
      .from('products')
      .select(`
        *,
        vendor:vendor_profiles(id, store_name, store_slug, store_logo),
        category:categories(id, name, slug)
      `, { count: 'exact' })
      .eq('status', 'active')
      .range(from, to);
    
    if (categorySlug) {
      query = query.eq('categories.slug', categorySlug);
    }
    
    if (vendorSlug) {
      query = query.eq('vendor_profiles.store_slug', vendorSlug);
    }
    
    if (search) {
      query = query.or(`name.ilike.%${search}%,description.ilike.%${search}%`);
    }
    
    if (featured) {
      query = query.eq('featured', true);
    }
    
    const sortColumn = sort === 'price' ? 'price' : sort === 'name' ? 'name' : 'created_at';
    query = query.order(sortColumn, { ascending: order === 'asc' });
    
    const { data: products, error, count } = await query;
    
    if (error) {
      throw error;
    }
    
    return new Response(JSON.stringify({
      success: true,
      products: products || [],
      pagination: {
        page,
        limit,
        total: count || 0,
        pages: Math.ceil((count || 0) / limit)
      }
    }), {
      status: 200,
      headers: { 'Content-Type': 'application/json' }
    });
    
  } catch (error) {
    console.error('Products list error:', error);
    return new Response(JSON.stringify({
      error: error instanceof Error ? error.message : 'Internal server error'
    }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
};

export const POST: APIRoute = async ({ request }) => {
  try {
    const authHeader = request.headers.get('authorization');
    const token = getTokenFromHeader(authHeader);
    const payload = verifyToken(token || '');
    
    if (!payload) {
      return new Response(JSON.stringify({ error: 'Unauthorized' }), {
        status: 401,
        headers: { 'Content-Type': 'application/json' }
      });
    }
    
    if (payload.role !== 'vendor' && payload.role !== 'admin') {
      return new Response(JSON.stringify({ error: 'Only vendors can create products' }), {
        status: 403,
        headers: { 'Content-Type': 'application/json' }
      });
    }
    
    const body = await request.json();
    const { name, slug, description, price, compare_at_price, category_id, images, inventory, sku } = body;
    
    if (!name || !slug || price === undefined) {
      return new Response(JSON.stringify({ error: 'Name, slug, and price are required' }), {
        status: 400,
        headers: { 'Content-Type': 'application/json' }
      });
    }
    
    const { data: vendor } = await supabaseAdmin
      .from('vendor_profiles')
      .select('id')
      .eq('user_id', payload.userId)
      .single();
    
    if (!vendor && payload.role !== 'admin') {
      return new Response(JSON.stringify({ error: 'Vendor profile not found' }), {
        status: 400,
        headers: { 'Content-Type': 'application/json' }
      });
    }
    
    const { data: product, error } = await supabaseAdmin
      .from('products')
      .insert({
        vendor_id: vendor?.id || null,
        category_id: category_id || null,
        name,
        slug,
        description: description || null,
        price,
        compare_at_price: compare_at_price || null,
        images: images || [],
        inventory: inventory || 0,
        sku: sku || null,
        status: 'active'
      })
      .select()
      .single();
    
    if (error) {
      throw error;
    }
    
    return new Response(JSON.stringify({
      success: true,
      product
    }), {
      status: 201,
      headers: { 'Content-Type': 'application/json' }
    });
    
  } catch (error) {
    console.error('Create product error:', error);
    return new Response(JSON.stringify({
      error: error instanceof Error ? error.message : 'Internal server error'
    }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
};
