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

export const GET: APIRoute = async ({ params }) => {
  try {
    const { slug } = params;
    
    if (!slug) {
      return new Response(JSON.stringify({ error: 'Product slug is required' }), {
        status: 400,
        headers: { 'Content-Type': 'application/json' }
      });
    }
    
    const { data: product, error } = await supabase
      .from('products')
      .select(`
        *,
        vendor:vendor_profiles(id, store_name, store_slug, store_logo, store_description),
        category:categories(id, name, slug, description),
        variants:product_variants(id, name, sku, price, inventory, options),
        reviews:reviews(id, rating, comment, user_id, created_at, user:users(id, name, avatar_url))
      `)
      .eq('slug', slug)
      .eq('status', 'active')
      .single();
    
    if (error || !product) {
      return new Response(JSON.stringify({ error: 'Product not found' }), {
        status: 404,
        headers: { 'Content-Type': 'application/json' }
      });
    }
    
    let avgRating = 0;
    let reviewCount = 0;
    
    if (product.reviews && product.reviews.length > 0) {
      const totalRating = product.reviews.reduce((sum: number, r: any) => sum + r.rating, 0);
      avgRating = totalRating / product.reviews.length;
      reviewCount = product.reviews.length;
    }
    
    return new Response(JSON.stringify({
      success: true,
      product: {
        ...product,
        avgRating: Math.round(avgRating * 10) / 10,
        reviewCount
      }
    }), {
      status: 200,
      headers: { 'Content-Type': 'application/json' }
    });
    
  } catch (error) {
    console.error('Get product error:', error);
    return new Response(JSON.stringify({
      error: error instanceof Error ? error.message : 'Internal server error'
    }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
};
