<?php
namespace Incoviba\Service\Money;

use Exception;
use DateTimeInterface;
use DateTimeImmutable;
use DateInterval;
use GuzzleHttp\Exception\GuzzleException;
use Psr\Http\Client\ClientInterface;
use Incoviba\Common\Implement\Exception\EmptyResponse;
use Incoviba\Common\Define\Money\Provider;

class Ine implements Provider
{
    protected string $uri = 'https://api-calculadora.ine.cl/ServiciosCalculadoraVariacion';
    public function __construct(protected ClientInterface $client) {}

    /**
     * @throws EmptyResponse
     * @throws Exception
     */
    public function get(string $money_symbol, DateTimeInterface $dateTime): float
    {
        $end = new DateTimeImmutable($dateTime->format('Y-m-1'));
        $start = $end->sub(new DateInterval('P1M'));
        return $this->getVar($start, $end);
    }

    /**
     * @throws EmptyResponse
     */
    public function getVar(DateTimeInterface $start, DateTimeInterface $end): float
    {
        $base = 1000000000;
        $request_query = [
            'mesInicio' => $start->format('m'),
            'AnioInicio' => $start->format('Y'),
            'mesTermino' => $end->format('m'),
            'AnioTermino' => $end->format('Y'),
            'valor_a_ajustar' => $base
        ];
        $request_uri = implode('?', [
            $this->uri,
            http_build_query($request_query),
            /*implode('&', array_map(function($val, $key) {
                return "{$key}={$val}";
            }, $request_query, array_keys($request_query)))*/
        ]);
        try {
            $response = $this->client->get($request_uri);
        } catch (GuzzleException) {
            throw new EmptyResponse($request_uri);
        }
        $body = $response->getBody();
        $json = json_decode($body->getContents());
        if (empty($json)) {
            throw new EmptyResponse($request_uri);
        }
        return ((int) str_replace('.', '', $json[0]->valorajustado) - $base) / $base;
    }
}
