
import {RewardDTO} from '../domain/RewardDTO';
import BalanceDTO from '../domain/BalanceDTO';
import Consts from '../Consts';
import { RateLimitService } from './RatelimitService';

export class  BalanceService {


  
  async getBalance(userId: string, adUnitId: string): Promise<RewardDTO | null> {

    if (!(await RateLimitService.canMakeRequest())) {
      console.log('the offerwall should be opened at least once');
      return null; // Block the request if the rate limit is exceeded
    }

    try {
      const url = `${Consts.API_URL}/balance/${userId}?adunit_id=${adUnitId}`;
      const response = await fetch(url, { method: 'GET' });
      console.log(url);
      if (!response.ok) {
        throw new Error(`HTTP error code: ${response.status}`);
      }

      const jsonResponse = await response.json();
      console.log(jsonResponse);
      const balanceDTO = BalanceDTO.parseFromJson(jsonResponse);

      if (!balanceDTO) {
        throw new Error('Invalid balance data');
      }

      const delta = balanceDTO.userLTVInVirtualCurrency - balanceDTO.lastSyncUserLTVInVirtualCurrency;

      if (delta !== 0) {
        return new RewardDTO(
          balanceDTO.userLTV - balanceDTO.lastSyncUserLTV,
          balanceDTO.userLTVInVirtualCurrency - balanceDTO.lastSyncUserLTVInVirtualCurrency
        );
      }

      return null; // No reward to give
    } catch (error) {
      console.error('Error fetching balance:', error);
      throw error; // Propagate error to be handled by the caller
    }
  }
}
