<?php
declare(strict_types=1);

namespace CronJobs;

use App\Core\App;
use App\Core\Database;
use App\Core\Logger;
use App\Modules\SportsActivity\Services\WaitlistAutoOfferService;

class SaWaitlistExpiryJob
{
    private Database $db;
    public function __construct(Database $db) { $this->db = $db; }

    public function shouldRun(): bool
    {
        return true;
    }

    public function run(): array
    {
        App::getInstance()->setDb($this->db);

        $now = date('Y-m-d H:i:s');

        $expired = $this->db->select(
            "SELECT id, group_id FROM sa_waitlist WHERE status = 'offered' AND expires_at < ?",
            [$now]
        );

        $expiredCount = 0;
        $offeredCount = 0;

        foreach ($expired as $entry) {
            $this->db->update('sa_waitlist', [
                'status'     => 'expired',
                'updated_at' => $now,
            ], 'id = ?', [(int) $entry['id']]);
            $expiredCount++;

            $offered = WaitlistAutoOfferService::offerNextInLine((int) $entry['group_id']);
            if ($offered) {
                $offeredCount++;
            }
        }

        Logger::info("SaWaitlistExpiryJob: {$expiredCount} expired, {$offeredCount} new offers made");
        return ['expired' => $expiredCount, 'offered' => $offeredCount];
    }
}
