<?php
namespace Incoviba\Command\Money;

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

#[Console\Attribute\AsCommand(
    name: 'money:ipc',
    description: 'Fetch IPC data from the API'
)]
class IPC extends Command
{
    public function execute(Console\Input\InputInterface $input, Console\Output\OutputInterface $output)
    {
        $this->logger->debug("Running {$this->getName()}");
        $lastMonth = (new DateTimeImmutable())->sub(new DateInterval('P1M'));
        $endLastYear = (new DateTimeImmutable())->sub(new DateInterval('P1Y'));
        $uri = '/api/money/ipc';
        $current = new DateTimeImmutable($lastMonth->format('Y-m-d'));
        while ($current->diff($endLastYear)->days > 30) {
            $data = [
                'start' => $endLastYear->format('Y-12-1'),
                'end' => $current->format('Y-m-1')
            ];
            $output->writeln("POST {$uri}");
            $response = $this->client->post($uri, [
                'body' => http_build_query($data),
                'headers' => ['Content-Type' => 'application/x-www-form-urlencoded']
            ]);
            $output->writeln("Response Code: {$response->getStatusCode()}");
            $current = $current->sub(new DateInterval('P1M'));
        }
        return Console\Command\Command::SUCCESS;
    }
}
