<?php
namespace App\Service;

use DateTimeInterface;
use Psr\Http\Message\ResponseInterface;
use Carbon\Carbon;
use GuzzleHttp\Client;

class Money
{
    public function __construct(protected Client $client) {}

    public function getUF(string|DateTimeInterface $date): object
    {
        $date = $this->parseDate($date);
        if (!$this->checkNextMonthValueCalculationByDate($date)) {
            return $this->emptyResult();
        }

        $response = $this->client->get('api/uf/value/' . $date->format('Y-m-d'));

        if (!$this->isOk($response)) {
            return $this->emptyResult();
        }

        $body = $response->getBody()->getContents();
        if (trim($response->getBody()) === '') {
            return $this->emptyResult();
        }
        return json_decode($body);
    }

    protected function parseDate(string|DateTimeInterface $date): DateTimeInterface
    {
        if (is_string($date)) {
            $date = Carbon::parse($date, config('app.timezone'));
        }
        return $date;
    }
    protected function checkNextMonthValueCalculationByDate(DateTimeInterface $date): bool
    {
        $next_m_9 = Carbon::today(config('app.timezone'))->copy()->endOfMonth()->addDays(9);
        $date = Carbon::parse($date);
        return $date->lessThan($next_m_9);
    }
    protected function isOk(ResponseInterface $response): bool
    {
        $statusCode = $response->getStatusCode();
        return $statusCode >= 200 and $statusCode < 300;
    }
    protected function emptyResult(): object
    {
        return (object) ['total' => 0];
    }
}
