import { apiRequest } from './client';

export interface StripePricingItem {
  price_id: string;
  product_id: string;
  name: string;
  amount: string;
  recurring?: {
    interval: string;
    interval_count: number;
  };
  metadata?: {
    grant_token?: string;
    [key: string]: any;
  };
  feature_list?: string[];
  is_highlight?: boolean;
  highlight_text?: string;
  metered_price_id?: string;
}

export interface StripePricingTableResponse {
  pricing_table_items: StripePricingItem[];
}

export interface CreditPlan {
  amountInCents: number;
  credits: number;
  popular?: boolean;
}

/**
 * 获取 Stripe 订阅套餐列表
 */
export async function getStripePlans(): Promise<{
  success: boolean;
  data?: StripePricingTableResponse;
  message?: string;
}> {
  try {
    const response = await apiRequest<{ success: boolean; data: StripePricingTableResponse }>(
      '/api/stripe/plans',
      {
        method: 'GET',
        requiresAuth: false,
      }
    );

    if (!response.success || !response.data) {
      return {
        success: false,
        message: 'Failed to fetch pricing data',
      };
    }

    return {
      success: true,
      data: response.data,
    };
  } catch (error) {
    console.error('Failed to fetch Stripe plans:', error);
    return {
      success: false,
      message: error instanceof Error ? error.message : 'Unknown error',
    };
  }
}

/**
 * 从 API 数据中提取计划名称列表
 */
export function getPlanNames(pricingData?: StripePricingTableResponse | null): string[] {
  if (!pricingData?.pricing_table_items) return [];

  return pricingData.pricing_table_items
    .filter(item => item.recurring?.interval === 'month')
    .map(item => item.name || 'basic');
}
