<?php

declare(strict_types=1);

namespace App\Jobs;

use App\Models\User;
use App\Services\AiBiography\AiBiographyService;
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;

/**
 * Generates or refreshes an AI biography for a creator asynchronously.
 *
 * Dispatched by:
 *   - Manual generate / regenerate API endpoints
 *   - Admin batch commands
 *   - Stale-detection refresh passes
 */
final class GenerateAiBiographyJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public int $tries = 2;

    public int $timeout = 90;

    public function __construct(
        public readonly int $userId,
        public readonly bool $force = false,
        public readonly ?string $provider = null,
    ) {
    }

    public function handle(AiBiographyService $biographyService): void
    {
        if ($this->provider !== null && $this->provider !== '') {
            config(['ai_biography.provider_override' => $this->provider]);
            config(['ai_biography.provider' => $this->provider]);
        }

        $user = User::query()
            ->where('id', $this->userId)
            ->where('is_active', true)
            ->whereNull('deleted_at')
            ->first();

        if ($user === null) {
            Log::warning('GenerateAiBiographyJob: user not found or inactive', ['user_id' => $this->userId]);
            return;
        }

        $result = $biographyService->regenerate($user, $this->force);

        if (! $result['success']) {
            Log::warning('GenerateAiBiographyJob: generation failed', [
                'user_id'  => $this->userId,
                'action'   => $result['action'],
                'errors'   => $result['errors'],
                'provider' => $this->provider,
            ]);
        }
    }
}
