<?php

namespace App\Service\ApiResourceBuilder\Mobyt;

use App\ApiResources\Mobyt\MobytUserStatus;
use App\Repository\Organization\OrganizationRepository;
use App\Service\Mobyt\MobytService;

class MobytUserStatusBuilder
{
    public function __construct(
        private MobytService $mobytService,
        private OrganizationRepository $organizationRepository,
    ) {}

    /**
     * Retrieve the status of the user from the Mobyt Api (via MobytService)
     *
     * @param int $organizationId
     * @return MobytUserStatus
     * @throws \JsonException
     */
    public function getUserStatus(int $organizationId): MobytUserStatus
    {
        $userStatus = new MobytUserStatus();
        $userStatus->setOrganizationId($organizationId);

        $organization = $this->organizationRepository->find($organizationId);
        if ($organization === null) {
            throw new \RuntimeException('Organization not found for user');
        }
        $parameters = $organization->getParameters();
        $mobytLogin = $parameters->getUsernameSMS();
        if (!$mobytLogin) {
            return $userStatus;
        }
        $mobytPassword = $parameters->getPasswordSMS();

        $userStatusData = $this->mobytService->getUserStatus($mobytLogin, $mobytPassword);
        $userStatus->setActive(true);
        $userStatus->setMoney($userStatusData['money']);

        $topQualitySmsAmount = 0;
        foreach ($userStatusData['sms'] as $_ => $smsTypeData) {
            // we only retrieve the 'top quality sms', which are identified by the letter N in the mobyt api
            if ($smsTypeData['type'] === 'N') {
                $topQualitySmsAmount = $smsTypeData['quantity'];
            }
        }
        $userStatus->setAmount($topQualitySmsAmount);
        return $userStatus;
    }
}
