<?php

namespace App\Models;

use CodeIgniter\Model;

class FootballLeagueSyncLogModel extends Model
{
    protected $table = 'football_league_sync_log';
    protected $primaryKey = 'id';
    protected $allowedFields = [
        'league_id',
        'season',
        'synced_teams_at',
        'synced_fixtures_from',
        'synced_fixtures_to',
        'synced_fixtures_at',
        'updated_at',
    ];
    protected $useTimestamps = false;

    public function getForLeague(int $leagueId, int $season): ?array
    {
        return $this->where('league_id', $leagueId)->where('season', $season)->first();
    }

    public function touchTeams(int $leagueId, int $season): void
    {
        $this->upsertLog($leagueId, $season, ['synced_teams_at' => date('Y-m-d H:i:s')]);
    }

    public function touchFixtures(int $leagueId, int $season, string $from, string $to): void
    {
        $this->upsertLog($leagueId, $season, [
            'synced_fixtures_from' => $from,
            'synced_fixtures_to' => $to,
            'synced_fixtures_at' => date('Y-m-d H:i:s'),
        ]);
    }

    protected function upsertLog(int $leagueId, int $season, array $fields): void
    {
        $existing = $this->getForLeague($leagueId, $season);
        $fields['updated_at'] = date('Y-m-d H:i:s');

        if ($existing) {
            $this->update($existing['id'], $fields);

            return;
        }

        $fields['league_id'] = $leagueId;
        $fields['season'] = $season;
        $this->insert($fields);
    }

    public function teamsFresh(int $leagueId, int $season, int $ttlSeconds): bool
    {
        $log = $this->getForLeague($leagueId, $season);
        if (!$log || empty($log['synced_teams_at'])) {
            return false;
        }

        return strtotime($log['synced_teams_at']) >= (time() - $ttlSeconds);
    }

    public function fixturesFresh(int $leagueId, int $season, string $from, string $to, int $ttlSeconds): bool
    {
        $log = $this->getForLeague($leagueId, $season);
        if (!$log || empty($log['synced_fixtures_at'])) {
            return false;
        }

        if (($log['synced_fixtures_from'] ?? '') !== $from || ($log['synced_fixtures_to'] ?? '') !== $to) {
            return false;
        }

        return strtotime($log['synced_fixtures_at']) >= (time() - $ttlSeconds);
    }
}
