import { createClient } from 'https://esm.sh/@supabase/supabase-js@2.57.4';

const corsHeaders = {
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
};

interface OrderQueryRequest {
  action: 'list' | 'search' | 'getById' | 'getByOrderNumber' | 'getOrderItems' | 'getUserOrders';
  orderId?: string;
  orderNumber?: string;
  userId?: string;
  status?: string;
  keyword?: string;
  startDate?: string;
  endDate?: string;
  limit?: number;
}

Deno.serve(async (req) => {
  // Handle CORS preflight requests
  if (req.method === 'OPTIONS') {
    return new Response(null, { headers: corsHeaders });
  }

  try {
    const supabaseUrl = Deno.env.get('SUPABASE_URL')!;
    const supabaseKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
    const supabase = createClient(supabaseUrl, supabaseKey);

    const requestData: OrderQueryRequest = await req.json();
    const { action, orderId, orderNumber, userId, status, keyword, startDate, endDate, limit = 50 } = requestData;

    console.log('Order query request:', { action, orderId, orderNumber, userId, status, keyword });

    switch (action) {
      case 'list': {
        // 查询所有订单（支持筛选条件）
        let query = supabase
          .from('orders')
          .select(`
            *,
            order_items (
              id,
              quantity,
              unit_price,
              product_id,
              products (
                id,
                name,
                image_url,
                brand,
                category
              )
            )
          `);
        
        if (status) {
          query = query.eq('status', status);
        }
        
        if (userId) {
          query = query.eq('user_id', userId);
        }
        
        if (startDate) {
          query = query.gte('created_at', startDate);
        }
        
        if (endDate) {
          query = query.lte('created_at', endDate);
        }
        
        const { data, error } = await query
          .order('created_at', { ascending: false })
          .limit(limit);
        
        if (error) throw error;
        
        return new Response(
          JSON.stringify({
            success: true,
            data: data || [],
            count: data?.length || 0
          }),
          { headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
        );
      }

      case 'search': {
        // 根据关键词搜索订单（订单号、用户ID）
        if (!keyword) {
          return new Response(
            JSON.stringify({ success: false, error: '缺少关键词参数' }),
            { status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
          );
        }

        const { data, error } = await supabase
          .from('orders')
          .select(`
            *,
            order_items (
              id,
              quantity,
              unit_price,
              product_id,
              products (
                id,
                name,
                image_url,
                brand,
                category
              )
            )
          `)
          .or(`order_number.ilike.%${keyword}%,tracking_number.ilike.%${keyword}%`)
          .order('created_at', { ascending: false })
          .limit(limit);
        
        if (error) throw error;
        
        return new Response(
          JSON.stringify({
            success: true,
            data: data || [],
            count: data?.length || 0
          }),
          { headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
        );
      }

      case 'getById': {
        // 根据ID查询订单详情
        if (!orderId) {
          return new Response(
            JSON.stringify({ success: false, error: '缺少订单ID参数' }),
            { status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
          );
        }

        const { data, error } = await supabase
          .from('orders')
          .select(`
            *,
            order_items (
              id,
              quantity,
              unit_price,
              product_id,
              products (
                id,
                name,
                image_url,
                brand,
                category,
                price
              )
            ),
            profiles (
              display_name,
              phone
            )
          `)
          .eq('id', orderId)
          .single();
        
        if (error) throw error;
        
        return new Response(
          JSON.stringify({
            success: true,
            data
          }),
          { headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
        );
      }

      case 'getByOrderNumber': {
        // 根据订单号查询订单
        if (!orderNumber) {
          return new Response(
            JSON.stringify({ success: false, error: '缺少订单号参数' }),
            { status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
          );
        }

        const { data, error } = await supabase
          .from('orders')
          .select(`
            *,
            order_items (
              id,
              quantity,
              unit_price,
              product_id,
              products (
                id,
                name,
                image_url,
                brand,
                category,
                price
              )
            ),
            profiles (
              display_name,
              phone
            )
          `)
          .eq('order_number', orderNumber)
          .single();
        
        if (error) throw error;
        
        return new Response(
          JSON.stringify({
            success: true,
            data
          }),
          { headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
        );
      }

      case 'getOrderItems': {
        // 获取订单项
        if (!orderId) {
          return new Response(
            JSON.stringify({ success: false, error: '缺少订单ID参数' }),
            { status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
          );
        }

        const { data, error } = await supabase
          .from('order_items')
          .select(`
            *,
            products (
              id,
              name,
              image_url,
              brand,
              category,
              price,
              stock_quantity
            )
          `)
          .eq('order_id', orderId);
        
        if (error) throw error;
        
        return new Response(
          JSON.stringify({
            success: true,
            data: data || [],
            count: data?.length || 0
          }),
          { headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
        );
      }

      case 'getUserOrders': {
        // 查询用户的所有订单
        if (!userId) {
          return new Response(
            JSON.stringify({ success: false, error: '缺少用户ID参数' }),
            { status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
          );
        }

        let query = supabase
          .from('orders')
          .select(`
            *,
            order_items (
              id,
              quantity,
              unit_price,
              product_id,
              products (
                id,
                name,
                image_url,
                brand,
                category
              )
            )
          `)
          .eq('user_id', userId);
        
        if (status) {
          query = query.eq('status', status);
        }
        
        const { data, error } = await query
          .order('created_at', { ascending: false })
          .limit(limit);
        
        if (error) throw error;
        
        return new Response(
          JSON.stringify({
            success: true,
            data: data || [],
            count: data?.length || 0
          }),
          { headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
        );
      }

      default:
        return new Response(
          JSON.stringify({ success: false, error: '不支持的操作类型' }),
          { status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
        );
    }
  } catch (error) {
    console.error('Order query error:', error);
    return new Response(
      JSON.stringify({
        success: false,
        error: (error instanceof Error ? error.message : String(error)) || '服务器内部错误'
      }),
      { status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
    );
  }
});
