<?php

namespace App\Jobs;

use App\Jobs\Tasks\GetNewsSerpTask;
use App\Jobs\Tasks\ParseNewsSerpDomainsTask;
use App\Models\Category;
use App\Models\SerpUrl;
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;

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

    /**
     * Create a new job instance.
     */
    public function __construct()
    {
        //
    }

    /**
     * Execute the job.
     */
    public function handle(): void
    {
        $category = Category::orderByRaw('CASE WHEN serp_at IS NULL THEN 1 ELSE 0 END DESC')
            ->orderBy('serp_at', 'asc')
            ->first();

        $news_serp_result = GetNewsSerpTask::handle($category, 'US');

        if (is_null($news_serp_result)) {
            Log::error(json_encode($category->toArray()));
            throw Exception('Failed to execute GetNewsSerpTask');
        }

        // We only take 1 record at a time
        if (ParseNewsSerpDomainsTask::handle($news_serp_result)) {
            $serp_url = SerpUrl::latest()->first();

            if (is_null($serp_url)) {
                Log::error(json_encode($serp_url->toArray()));
                throw Exception('Failed to execute ParseNewsSerpDomainsTask');
            }

            GenerateArticleJob::dispatch($serp_url)->onQueue('default')->onConnection('default');
        }
    }
}
