import { supabase } from "@/integrations/supabase/client";

export interface CouponQueryParams {
  search?: string;
  type?: 'percentage' | 'fixed';
  scope?: 'all' | 'category' | 'product' | 'brand';
  available_only?: boolean;
  limit?: number;
}

export interface Coupon {
  id: string;
  code: string;
  name: string;
  description?: string;
  type: string;
  discount_value: number;
  min_purchase_amount?: number;
  max_discount_amount?: number;
  end_date: string;
  scope: string;
  received?: boolean;
}

/**
 * 查询可用优惠券
 */
export async function queryCoupons(params: CouponQueryParams = {}): Promise<Coupon[]> {
  try {
    const { data, error } = await supabase.functions.invoke('coupon-query', {
      body: params
    });

    if (error) {
      console.error('查询优惠券失败:', error);
      return [];
    }

    if (!data?.success) {
      console.error('优惠券查询返回失败:', data);
      return [];
    }

    console.log('优惠券查询成功，返回数量:', data.count);
    return data.data || [];
  } catch (error) {
    console.error('优惠券查询异常:', error);
    return [];
  }
}

/**
 * 获取新用户优惠券
 */
export async function getWelcomeCoupons(): Promise<Coupon[]> {
  return queryCoupons({
    search: '新用户',
    available_only: true,
    limit: 3
  });
}

/**
 * 获取全场优惠券
 */
export async function getAllCoupons(): Promise<Coupon[]> {
  return queryCoupons({
    scope: 'all',
    available_only: true,
    limit: 5
  });
}

/**
 * 根据关键词搜索优惠券
 */
export async function searchCoupons(keyword: string): Promise<Coupon[]> {
  return queryCoupons({
    search: keyword,
    available_only: true,
    limit: 5
  });
}
