<?php

namespace App\Jobs;

use App\Services\CronLogService;
use App\Services\RankService;
use Carbon\Carbon;
use Exception;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class RunRankEngineJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public function __construct(public readonly string $runDate)
    {
    }

    public function handle(RankService $rankService, CronLogService $cronLogService): void
    {
        $runDate = Carbon::parse($this->runDate);
        $runKey = 'rank-engine-'.$runDate->format('Ymd');
        $log = $cronLogService->start('rank-engine', $runKey, ['run_date' => $runDate->toDateString()]);

        try {
            $rankService->recalculateAll($runDate);
            $cronLogService->finish($log, 'success', 'Rank calculation completed.');
        } catch (Exception $exception) {
            $cronLogService->finish($log, 'failed', null, $exception->getMessage());
            throw $exception;
        }
    }
}
