/**
 * API для реферальной системы
 */

import apiClient from '@/lib/api-client';

export interface ReferralProfile {
  referral_code: string;
  referral_link: string;
  total_points: number;
}

export interface ReferralStats {
  referral_code: string;
  total_points: number;
  current_level: { level: number; name: string };
  referrals: { direct: number; indirect: number; total: number };
  earnings: { total: number };
  bonus_account: { balance: number };
}

export async function getReferralProfile(): Promise<ReferralProfile | null> {
  try {
    const response = await apiClient.get<any>('/referrals/my_profile/');
    return response.data;
  } catch {
    return null;
  }
}

export async function getReferralStats(): Promise<ReferralStats | null> {
  try {
    const response = await apiClient.get<any>('/referrals/stats/');
    return response.data;
  } catch {
    return null;
  }
}

/** Установить реферера по коду (после регистрации). */
export async function setReferrer(referralCode: string): Promise<void> {
  await apiClient.post('/referrals/set_referrer/', { referral_code: referralCode.trim() });
}

/** Ключ в localStorage для реферального кода (после перехода по ссылке /register?ref=CODE). */
export const REFERRAL_STORAGE_KEY = 'referral_code';

export interface MyReferralItem {
  email: string;
  level: string;
  total_points: number;
  created_at: string;
}

export interface MyReferralsResponse {
  direct: MyReferralItem[];
  indirect: MyReferralItem[];
}

/** Список приглашённых рефералов (прямые и непрямые). */
export async function getMyReferrals(): Promise<MyReferralsResponse> {
  const response = await apiClient.get<MyReferralsResponse>('/referrals/my_referrals/');
  return response.data;
}
