<?php

// SPDX-FileCopyrightText: 2021 Icinga GmbH <https://icinga.com>
// SPDX-License-Identifier: GPL-3.0-or-later

namespace Icinga\Module\Icingadb\ProvidedHook;

use Exception;
use Icinga\Application\Hook\HealthHook;
use Icinga\Module\Icingadb\Common\Backend;
use Icinga\Module\Icingadb\Common\Database;
use Icinga\Module\Icingadb\Common\IcingaRedis;
use Icinga\Module\Icingadb\Model\Instance;

class RedisHealth extends HealthHook
{
    use Database;

    public function getName(): string
    {
        return 'Redis';
    }

    public function checkHealth()
    {
        try {
            $lastIcingaHeartbeat = IcingaRedis::getLastIcingaHeartbeat();
            if ($lastIcingaHeartbeat === null) {
                $lastIcingaHeartbeat = time();
            }

            $server = Backend::getRedis()->getConnection()->info('Server')['Server'];
            $instance = Instance::on($this->getDb())->columns('heartbeat')->first();

            if ($instance === null) {
                $this->setState(self::STATE_UNKNOWN);
                $this->setMessage(t(
                    'Can\'t check Redis: Icinga DB is not running or not writing into the database'
                    . ' (make sure the icinga feature "icingadb" is enabled)'
                ));

                return;
            }

            $this->setMetrics($server);

            $outdatedDbHeartbeat = $instance->heartbeat->getTimestamp() < time() - 60;
            if (! $outdatedDbHeartbeat || $instance->heartbeat->getTimestamp() <= $lastIcingaHeartbeat) {
                $this->setState(self::STATE_OK);
                $this->setMessage(sprintf(
                    t('Redis available and in sync with Icinga. (Version: %s)'),
                    $server['redis_version'] ?? t('N/A')
                ));
            } elseif ($instance->heartbeat->getTimestamp() > $lastIcingaHeartbeat) {
                $this->setState(self::STATE_CRITICAL);
                $this->setMessage(t('Redis outdated. Make sure Icinga 2 is running and connected to Redis.'));
            }
        } catch (Exception $e) {
            $this->setState(self::STATE_CRITICAL);
            $this->setMessage(sprintf(t("Can't connect to Redis: %s"), $e->getMessage()));
        }
    }
}
