<?php

declare(strict_types=1);

namespace App\Jobs;

use App\Services\RankingService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 * RankComputeArtworkScoresJob
 *
 * Runs hourly. Queries raw artwork signals (views, favourites, downloads,
 * age, tags) in batches, computes the three ranking scores using
 * RankingService::computeScores(), and bulk-upserts the results into
 * rank_artwork_scores.
 *
 * No N+1: all signals are resolved via a single pre-aggregated JOIN query,
 * chunked by artwork id.
 */
class RankComputeArtworkScoresJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public int $timeout = 1800;     // 30 min max
    public int $tries   = 2;

    private const CHUNK_SIZE = 500;

    public function handle(RankingService $ranking): void
    {
        $modelVersion = config('ranking.model_version', 'rank_v1');
        $total        = 0;
        $now          = now()->toDateTimeString();

        $ranking->artworkSignalsQuery()
            ->orderBy('a.id')
            ->chunk(self::CHUNK_SIZE, function ($rows) use ($ranking, $modelVersion, $now, &$total): void {
                $rows = collect($rows);

                if ($rows->isEmpty()) {
                    return;
                }

                $upserts = $rows->map(function ($row) use ($ranking, $modelVersion, $now): array {
                    $scores = $ranking->computeScores($row);

                    return [
                        'artwork_id'      => (int) $row->id,
                        'score_trending'  => $scores['score_trending'],
                        'score_new_hot'   => $scores['score_new_hot'],
                        'score_best'      => $scores['score_best'],
                        'model_version'   => $modelVersion,
                        'computed_at'     => $now,
                    ];
                })->all();

                DB::table('rank_artwork_scores')->upsert(
                    $upserts,
                    ['artwork_id'],                                          // unique key
                    ['score_trending', 'score_new_hot', 'score_best',       // update these
                     'model_version', 'computed_at']
                );

                $total += count($upserts);
            });

        Log::info('RankComputeArtworkScoresJob: finished', [
            'total_updated' => $total,
            'model_version' => $modelVersion,
        ]);
    }
}
