import api from '@/lib/api';

export interface DiscountValidationResponse {
  valid: boolean;
  type?: 'percentage' | 'fixed';
  value?: number;
  code?: string;
  discount_amount?: number;
  min_order_amount?: number;
  message?: string;
}

export const discountService = {
  /**
   * Validate a promotion/discount code
   * @param code - The promotion code to validate
   * @param orderAmount - Optional order amount for full validation
   * @param productId - Optional product ID for product-specific discounts
   */
  async validateCode(
    code: string,
    orderAmount?: number,
    productId?: number
  ): Promise<DiscountValidationResponse> {
    try {
      const response = await api.post<DiscountValidationResponse>('/discounts/validate', {
        code,
        order_amount: orderAmount,
        product_id: productId,
      });
      
      return response;
    } catch (error: unknown) {
      // Handle validation errors from API
      const err = error as { response?: { status?: number; data?: { message?: string } } };
      if (err.response?.status === 400 && err.response?.data) {
        return {
          valid: false,
          message: err.response.data.message || 'Invalid promotion code',
        };
      }
      
      throw error;
    }
  },

  /**
   * Calculate discount amount based on type and value
   * @param type - 'percentage' or 'fixed'
   * @param value - Discount value
   * @param amount - Order/product amount
   */
  calculateDiscount(type: 'percentage' | 'fixed', value: number, amount: number): number {
    if (type === 'percentage') {
      return amount * (value / 100);
    }
    return Math.min(value, amount);
  },

  /**
   * Format discount display text
   * @param type - 'percentage' or 'fixed'
   * @param value - Discount value
   */
  formatDiscountText(type: 'percentage' | 'fixed', value: number): string {
    if (type === 'percentage') {
      return `${value}% off`;
    }
    return `SAR ${value} off`;
  },
};

export default discountService;
