import { api } from '../api';

export interface Coupon {
  id: number;
  code: string;
  amount: number;
  discount_type: 'percent' | 'fixed_cart' | 'fixed_product';
  description: string;
  usage_count: number;
  usage_limit: number | null;
  date_expires: string | null;
  individual_use?: boolean;
  product_ids?: number[];
  excluded_product_ids?: number[];
  usage_limit_per_user?: number | null;
  limit_usage_to_x_items?: number | null;
  free_shipping?: boolean;
  product_categories?: number[];
  excluded_product_categories?: number[];
  exclude_sale_items?: boolean;
  minimum_amount?: number | null;
  maximum_amount?: number | null;
  email_restrictions?: string[];
}

export interface CouponListResponse {
  coupons: Coupon[];
  total: number;
  page: number;
  per_page: number;
  total_pages: number;
}

export interface CouponFormData {
  code: string;
  amount: number;
  discount_type: 'percent' | 'fixed_cart' | 'fixed_product';
  description?: string;
  date_expires?: string | null;
  individual_use?: boolean;
  product_ids?: number[];
  excluded_product_ids?: number[];
  usage_limit?: number | null;
  usage_limit_per_user?: number | null;
  limit_usage_to_x_items?: number | null;
  free_shipping?: boolean;
  product_categories?: number[];
  excluded_product_categories?: number[];
  exclude_sale_items?: boolean;
  minimum_amount?: number | null;
  maximum_amount?: number | null;
  email_restrictions?: string[];
}

export const CouponsApi = {
  /**
   * List coupons with pagination and filtering
   */
  list: async (params?: {
    page?: number;
    per_page?: number;
    search?: string;
    discount_type?: string;
  }): Promise<CouponListResponse> => {
    return api.get('/coupons', params);
  },

  /**
   * Get single coupon
   */
  get: async (id: number): Promise<Coupon> => {
    return api.get(`/coupons/${id}`);
  },

  /**
   * Create new coupon
   */
  create: async (data: CouponFormData): Promise<Coupon> => {
    return api.post('/coupons', data);
  },

  /**
   * Update coupon
   */
  update: async (id: number, data: Partial<CouponFormData>): Promise<Coupon> => {
    return api.put(`/coupons/${id}`, data);
  },

  /**
   * Delete coupon
   */
  delete: async (id: number, force: boolean = false): Promise<{ success: boolean; id: number }> => {
    return api.del(`/coupons/${id}?force=${force ? 'true' : 'false'}`);
  },
};
