<?php
namespace Incoviba\Service;

use DateTimeInterface;
use DateTimeImmutable;
use DateInterval;
use Incoviba\Common\Implement\Exception\EmptyRedis;

class IPC
{
    protected string $redisKey = 'ipc';
    public function __construct(protected Redis $redisService, protected Money $moneyService) {}

    public function get(DateTimeInterface $from, DateTimeInterface $to = new DateTimeImmutable()): float
    {
        $now = new DateTimeImmutable();
        if ($to > $now) {
            return 0;
        }
        $dateKey = "{$from->format('Y-m')}|{$to->format('Y-m')}";
        $ipcs = [];
        try {
            $ipcs = json_decode($this->redisService->get($this->redisKey), JSON_OBJECT_AS_ARRAY);
            if (!isset($ipcs[$dateKey])) {
                throw new EmptyRedis($this->redisKey);
            }
        } catch (EmptyRedis) {
            $ipc = $this->moneyService->getIPC($from, $to);
            if ($ipc === -1.0) {
                return 0;
            }
            $ipcs[$dateKey] = $ipc;
            ksort($ipcs);
            $this->redisService->set($this->redisKey, json_encode($ipcs), 60 * 60 * 24 * 30);
        }
        return $ipcs[$dateKey];
    }
    public function readjust(float $base, DateTimeInterface $from, DateTimeInterface $to = new DateTimeImmutable()):float
    {
        if (($ipc = $this->get($from, $to->sub(new DateInterval('P1M')))) === 0.0) {
            return $base;
        }
        return $base * (1 + $ipc);
    }
}
