import { serve } from "https://deno.land/std@0.168.0/http/server.ts";
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 CouponQueryParams {
  search?: string;
  type?: 'percentage' | 'fixed';
  scope?: 'all' | 'category' | 'product' | 'brand';
  available_only?: boolean;
  limit?: number;
}

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 supabaseServiceKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY');

    if (!supabaseUrl || !supabaseServiceKey) {
      throw new Error('Missing Supabase configuration');
    }

    const supabase = createClient(supabaseUrl, supabaseServiceKey);

    // Get user ID if authenticated (optional)
    let userId: string | null = null;
    const authHeader = req.headers.get('Authorization');
    if (authHeader) {
      const token = authHeader.replace('Bearer ', '');
      const { data: { user } } = await supabase.auth.getUser(token);
      userId = user?.id || null;
    }

    const requestData = await req.json();
    const { 
      search,
      type,
      scope,
      available_only = true,
      limit = 20
    }: CouponQueryParams = requestData;

    console.log('Coupon query params:', { search, type, scope, available_only, limit, userId });

    const now = new Date().toISOString();

    // Build query
    let query = supabase
      .from('coupons')
      .select('*');

    // Filter by active status and date range if available_only
    if (available_only) {
      query = query
        .eq('status', 'active')
        .lte('start_date', now)
        .gte('end_date', now)
        .gt('total_quantity', 0);
    }

    // Filter by type
    if (type) {
      query = query.eq('type', type);
    }

    // Filter by scope
    if (scope) {
      query = query.eq('scope', scope);
    }

    // Search by name, code, or description
    if (search && search.trim()) {
      query = query.or(`name.ilike.%${search}%,code.ilike.%${search}%,description.ilike.%${search}%`);
    }

    // Order by discount value (highest first) and limit
    query = query
      .order('discount_value', { ascending: false })
      .limit(limit);

    const { data: coupons, error } = await query;

    if (error) {
      console.error('Query coupons error:', error);
      throw error;
    }

    // If user is authenticated, check which coupons they've already received
    let userCoupons: any[] = [];
    if (userId) {
      const { data: userCouponData } = await supabase
        .from('user_coupons')
        .select('coupon_id, status')
        .eq('user_id', userId);
      
      userCoupons = userCouponData || [];
    }

    // Format coupons for frontend display
    const formattedCoupons = coupons?.map(coupon => {
      const userCoupon = userCoupons.find(uc => uc.coupon_id === coupon.id);
      const remainingQuantity = coupon.total_quantity - (coupon.used_quantity || 0);
      const isAvailable = remainingQuantity > 0 && 
                         new Date(coupon.start_date) <= new Date() && 
                         new Date(coupon.end_date) >= new Date() &&
                         coupon.status === 'active';

      return {
        id: coupon.id,
        name: coupon.name,
        code: coupon.code,
        description: coupon.description,
        type: coupon.type,
        discount_value: coupon.discount_value,
        scope: coupon.scope,
        scope_ids: coupon.scope_ids,
        min_purchase_amount: coupon.min_purchase_amount,
        max_discount_amount: coupon.max_discount_amount,
        per_user_limit: coupon.per_user_limit,
        start_date: coupon.start_date,
        end_date: coupon.end_date,
        remaining_quantity: remainingQuantity,
        is_available: isAvailable,
        user_received: !!userCoupon,
        user_coupon_status: userCoupon?.status || null,
        // Human-readable display text
        discount_display: coupon.type === 'percentage' 
          ? `${coupon.discount_value}% 折扣`
          : `¥${coupon.discount_value} 优惠`,
        validity_display: `${new Date(coupon.start_date).toLocaleDateString()} - ${new Date(coupon.end_date).toLocaleDateString()}`,
        condition_display: coupon.min_purchase_amount 
          ? `满 ¥${coupon.min_purchase_amount} 可用`
          : '无门槛',
        scope_display: coupon.scope === 'all' ? '全场通用' 
                     : coupon.scope === 'category' ? '分类专用'
                     : coupon.scope === 'product' ? '商品专用'
                     : '品牌专用',
      };
    }) || [];

    return new Response(
      JSON.stringify({ 
        success: true, 
        data: formattedCoupons,
        count: formattedCoupons.length,
        user_authenticated: !!userId
      }),
      { 
        status: 200,
        headers: { ...corsHeaders, 'Content-Type': 'application/json' }
      }
    );

  } catch (error) {
    console.error('Coupon query error:', error);
    return new Response(
      JSON.stringify({ 
        error: ((error instanceof Error ? error.message : String(error))) || 'Internal server error',
        details: String(error)
      }),
      { 
        status: 500,
        headers: { ...corsHeaders, 'Content-Type': 'application/json' }
      }
    );
  }
});
