<?php

declare(strict_types=1);

namespace App\Jobs;

use App\Models\Category;
use App\Models\ContentType;
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\Log;

/**
 * RankBuildListsJob
 *
 * Runs hourly (after RankComputeArtworkScoresJob).
 *
 * Builds ordered artwork_id arrays for:
 *  • global        – trending, new_hot, best
 *  • each category – trending, new_hot, best
 *  • each content_type – trending, new_hot, best
 *
 * Applies author-diversity cap (max 3 per author in a list of 50).
 * Stores results in rank_lists and busts relevant Redis keys.
 */
class RankBuildListsJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public int $timeout = 300;
    public int $tries   = 1;

    public function handle(): void
    {
        $scopesDispatched = 0;

        RankBuildScopeListsJob::dispatch('global', 0);
        $scopesDispatched++;

        Category::query()
            ->select(['id'])
            ->where('is_active', true)
            ->orderBy('id')
            ->chunk(200, function ($categories) use (&$scopesDispatched): void {
                foreach ($categories as $cat) {
                    RankBuildScopeListsJob::dispatch('category', (int) $cat->id);
                    $scopesDispatched++;
                }
            });

        ContentType::query()
            ->select(['id'])
            ->orderBy('id')
            ->chunk(50, function ($ctypes) use (&$scopesDispatched): void {
                foreach ($ctypes as $ct) {
                    RankBuildScopeListsJob::dispatch('content_type', (int) $ct->id);
                    $scopesDispatched++;
                }
            });

        Log::info('RankBuildListsJob: dispatched scope rebuild jobs', [
            'scopes_dispatched' => $scopesDispatched,
            'model_version'     => config('ranking.model_version', 'rank_v1'),
        ]);
    }
}
