<?php

namespace App\Jobs\Tasks;

use App\Helpers\FirstParty\DFS\DFSSerp;
use App\Helpers\FirstParty\OSSUploader\OSSUploader;
use App\Helpers\ThirdParty\DFS\SettingSerpLiveAdvanced;
use App\Models\NewsSerpResult;
use App\Models\ServiceCostUsage;
use DFSClientV3\DFSClient;
use Exception;
use Illuminate\Support\Facades\Log;

class BrowseDFSLatestNewsTask
{
    public static function handle(string $keyword, $country_iso)
    {
        $country_name = get_country_name_by_iso($country_iso);

        // $client = new DFSClient(
        //     config('dataforseo.login'),
        //     config('dataforseo.password'),
        //     config('dataforseo.timeout'),
        //     config('dataforseo.api_version'),
        //     config('dataforseo.url'),
        // );

        // // You will receive SERP data specific to the indicated keyword, search engine, and location parameters
        // $serp_model = new SettingSerpLiveAdvanced();

        // $serp_model->setSe('google');
        // $serp_model->setSeType('news');
        // $serp_model->setSearchParam('&tbs=qdr:d');
        // $serp_model->setKeyword($keyword);
        // $serp_model->setLocationName($country_name);
        // $serp_model->setDepth(100);
        // $serp_model->setLanguageCode('en');
        // $serp_res = $serp_model->getAsJson();

        $serp_res = DFSSerp::liveAdvanced('google', 'news', $keyword, $country_name, 'en', 100, '&tbs=qdr:d');

        try {
            $serp_obj = json_decode($serp_res, false, 512, JSON_THROW_ON_ERROR);

            if ($serp_obj?->status_code == 20000) {

                $service_cost_usage = new ServiceCostUsage;
                $service_cost_usage->cost = $serp_obj->cost;
                $service_cost_usage->name = 'dataforseo-GoogleSerpApiAdvancedLiveNews';
                $service_cost_usage->reference_1 = 'google';
                $service_cost_usage->reference_2 = 'news';
                $service_cost_usage->output = $serp_obj;
                $service_cost_usage->input_1 = $country_name;
                $service_cost_usage->input_2 = $keyword;
                $service_cost_usage->save();

                $json_file_name = config('platform.dataset.news.news_serp.file_prefix').str_slug($keyword).'-'.epoch_now_timestamp().'.json';

                $upload_status = OSSUploader::uploadJson(
                    config('platform.dataset.news.news_serp.driver'),
                    config('platform.dataset.news.news_serp.path'),
                    $json_file_name,
                    $serp_obj);

                if ($upload_status) {

                    $news_serp_result = new NewsSerpResult;
                    $news_serp_result->serp_provider = 'dfs';
                    $news_serp_result->serp_se = 'google';
                    $news_serp_result->serp_se_type = 'news';
                    $news_serp_result->serp_keyword = $keyword;
                    $news_serp_result->serp_country_iso = strtoupper($country_iso);
                    $news_serp_result->serp_cost = $serp_obj?->cost;
                    $news_serp_result->result_count = $serp_obj?->tasks[0]?->result[0]?->items_count;
                    $news_serp_result->filename = $json_file_name;
                    $news_serp_result->status = 'initial';
                    $news_serp_result->save();

                    return $news_serp_result;
                } else {
                    throw new Exception('Uploading failed', 1);
                }
            }
        } catch (Exception $e) {
            Log::error(json_encode($serp_obj));
            inspector()->reportException($e);

            return null;
        }

    }
}
