<?php

declare(strict_types=1);

namespace Autogedal\FeedMonitor\Model\Firebear;

use Magento\Framework\App\ResourceConnection;

/**
 * Firebear's own import history (firebear_import_history): one row per import, finished_at empty while it runs or
 * when the process died.
 */
class ImportHistory
{
    public function __construct(
        private readonly ResourceConnection $resource
    ) {
    }

    /**
     * The import that wrote $file (each run has its own file / log), as in getLatest().
     *
     * @return array{history_id: int, file: string, started: int, finished: int|null}|null
     */
    public function getByFile(int $jobId, string $file): ?array
    {
        $connection = $this->resource->getConnection();

        return $this->toArray($connection->fetchRow($this->select()
            ->where('job_id = ?', $jobId)
            ->where('file = ?', $file)
            ->order('history_id DESC')
            ->limit(1)));
    }

    /**
     * Last import of a job; times as UTC timestamps (the columns are TIMESTAMP, read independently of the session
     * time zone).
     *
     * @return array{history_id: int, file: string, started: int, finished: int|null}|null
     */
    public function getLatest(int $jobId): ?array
    {
        $connection = $this->resource->getConnection();

        return $this->toArray($connection->fetchRow($this->select()
            ->where('job_id = ?', $jobId)
            ->order('history_id DESC')
            ->limit(1)));
    }

    private function select(): \Magento\Framework\DB\Select
    {
        return $this->resource->getConnection()->select()
            ->from($this->resource->getTableName('firebear_import_history'), [
                'history_id',
                'file',
                'started' => new \Zend_Db_Expr('UNIX_TIMESTAMP(started_at)'),
                'finished' => new \Zend_Db_Expr('UNIX_TIMESTAMP(finished_at)'),
            ]);
    }

    /**
     * @param array<string, mixed>|false $row
     */
    private function toArray(array|false $row): ?array
    {
        if (!$row) {
            return null;
        }

        return [
            'history_id' => (int)$row['history_id'],
            'file' => (string)$row['file'],
            'started' => (int)$row['started'],
            'finished' => $row['finished'] !== null && (int)$row['finished'] > 0 ? (int)$row['finished'] : null,
        ];
    }
}
