<?php
declare(strict_types=1);

namespace CronJobs;

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

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

    public function shouldRun(): bool
    {
        return (int) date('w') === 0;
    }

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

        $fromDate = date('Y-m-d');
        $toDate = date('Y-m-d', strtotime('+4 weeks'));

        $groups = $this->db->select(
            "SELECT DISTINCT gs.group_id
             FROM sa_group_schedule gs
             INNER JOIN sa_groups g ON g.id = gs.group_id
             WHERE gs.is_active = 1 AND g.status = 'active' AND g.is_archived = 0",
            []
        );

        $totalGenerated = 0;
        $totalSkipped = 0;
        $errors = 0;

        foreach ($groups as $g) {
            $result = ScheduleGeneratorService::generateForGroup((int) $g['group_id'], $fromDate, $toDate);
            if ($result['success']) {
                $totalGenerated += (int) ($result['generated'] ?? 0);
                $totalSkipped += (int) ($result['skipped'] ?? 0);
            } else {
                $errors++;
            }
        }

        Logger::info("SaSessionForwardGeneratorJob: {$totalGenerated} sessions generated, {$totalSkipped} skipped, {$errors} errors across " . count($groups) . " groups");
        return [
            'groups_processed' => count($groups),
            'generated'        => $totalGenerated,
            'skipped'          => $totalSkipped,
            'errors'           => $errors,
        ];
    }
}
