<?php

defined('APP_BOOTSTRAPPED') or exit('No direct access.');

class ProviderAccountService
{
    private $userRepository;

    public function __construct(UserRepository $userRepository)
    {
        $this->userRepository = $userRepository;
    }

    public function createUser($userId, $apiProvider, array $options = array())
    {
        $apiProvider = strtolower(trim((string) $apiProvider));

        $playerCode = $this->userRepository->getPlayerCode(
            $userId,
            $apiProvider
        );

        if ($playerCode === null || $playerCode === '') {
            $playerCode = $this->generatePlayerCode(
                $apiProvider,
                $userId
            );
        }

        $result = GameApi::adapter($apiProvider)->createUser(
            $playerCode,
            $options
        );

        if (
            isset($result['success']) &&
            $result['success'] === true
        ) {
            $this->userRepository->savePlayerCode(
                $userId,
                $apiProvider,
                $playerCode
            );
        }

        return $result;
    }

    public function getBalance($userId, $apiProvider)
    {
        $apiProvider = strtolower(trim((string) $apiProvider));

        $playerCode = $this->userRepository->getPlayerCode(
            $userId,
            $apiProvider
        );

        if ($playerCode === null || $playerCode === '') {
            throw new GameApiException(
                'User belum memiliki akun provider ' .
                strtoupper($apiProvider) . '.',
                404
            );
        }

        return GameApi::adapter($apiProvider)->getBalance(
            $playerCode
        );
    }

    private function generatePlayerCode($apiProvider, $userId)
    {
        $prefix = $apiProvider === 'sgx' ? 'S' : 'N';

        return $prefix .
            str_pad((string) (int) $userId, 10, '0', STR_PAD_LEFT);
    }
}
