<?php

declare(strict_types=1);

namespace Autogedal\FeedMonitor\Model;

use Magento\Framework\App\ResourceConnection;

/**
 * Last sign of life of the Magento cron: the most recent job start or end in cron_schedule.
 */
class Heartbeat
{
    public function __construct(
        private readonly ResourceConnection $resource
    ) {
    }

    /**
     * @return int|null UTC timestamp, null when cron_schedule has no executed job
     */
    public function getLastActivity(): ?int
    {
        $connection = $this->resource->getConnection();
        $table = $this->resource->getTableName('cron_schedule');
        $last = $connection->fetchOne($connection->select()->from($table, [
            'last' => new \Zend_Db_Expr('GREATEST(COALESCE(MAX(executed_at), \'1970-01-01\'), COALESCE(MAX(finished_at), \'1970-01-01\'))'),
        ]));

        $timestamp = $last ? (int)strtotime($last . ' UTC') : 0;

        return $timestamp > 0 ? $timestamp : null;
    }
}
