<?php
namespace Incoviba\Command\Money\UF;

use DateTimeImmutable;
use Symfony\Component\Console;
use Incoviba\Common\Alias\Command;

#[Console\Attribute\AsCommand(
    name: 'money:uf:update',
    description: 'Update UF value'
)]
class Update extends Command
{
    public function execute(Console\Input\InputInterface $input, Console\Output\OutputInterface $output)
    {
        $this->logger->debug("Running {$this->getName()}");
        $url = '/api/money/ufs';
        $response = $this->client->get($url);
        $output->writeln("GET {$url}");
        if ($response->getStatusCode() !== 200) {
            $this->logger->error("Error: [{$response->getStatusCode()}] {$response->getReasonPhrase()}");
            return Console\Command\Command::FAILURE;
        }
        $data = json_decode($response->getBody()->getContents(), JSON_OBJECT_AS_ARRAY)['ufs'];
        $zeros = [];
        foreach ($data as $date => $value) {
            if ($value === 0) {
                $zeros[] = $date;
            }
        }
        if (count($zeros) > 0) {
            $output->writeln('Updating ' . count($zeros) . ' UFs');
            $uri = '/api/money/ufs';
            $response = $this->client->post($uri, [
                'body' => http_build_query(['fechas' => $zeros]),
                'headers' => ['Content-Type' => 'application/x-www-form-urlencoded']
            ]);
            $output->writeln("POST {$uri}");
            if ($response->getStatusCode() !== 200) {
                $this->logger->error("Error: [{$response->getStatusCode()}] {$response->getReasonPhrase()}");
                return Console\Command\Command::FAILURE;
            }
            $body = json_decode($response->getBody()->getContents(), JSON_OBJECT_AS_ARRAY);
            $output->writeln('Updated ' . count($body['ufs']) . ' UFs');
        }
        return Console\Command\Command::SUCCESS;
    }
}
