<?php

namespace App\Jobs\Tasks;

use App\Helpers\FirstParty\OpenAI\OpenAI;
use App\Jobs\GenerateArticleFeaturedImageJob;
use App\Models\Author;
use App\Models\Post;
use App\Models\PostCategory;
use App\Models\SerpUrl;
use Exception;

class GenerateArticleTask
{
    public static function handle(SerpUrl $serp_url)
    {

        // $ai_titles = OpenAI::suggestArticleTitles($serp_url->title, $serp_url->description, 1);

        // if (is_null($ai_titles)) {
        //     return self::saveAndReturnSerpProcessStatus($serp_url, -2);
        // }

        // $suggestion = null;

        // // dump($ai_titles);

        // try {
        //     $random_key = array_rand($ai_titles?->suggestions, 1);

        //     $suggestion = $ai_titles->suggestions[$random_key];

        // } catch (Exception $e) {
        //     return self::saveAndReturnSerpProcessStatus($serp_url, -1);
        // }

        // if (is_null($suggestion)) {
        //     return self::saveAndReturnSerpProcessStatus($serp_url, -3);
        // }

        $ai_suggestion = null;

        $count = 0;

        while ((!isset($ai_suggestion?->article_type)) || (!isset($ai_suggestion?->short_title)) || (!isset($ai_suggestion?->main_keyword)) || (!isset($ai_suggestion?->photo_keywords)) || (!isset($ai_suggestion?->description)) || (!isset($ai_suggestion?->title)))
        {
          if ($count >= 3)
          {
            Log::error(serialize($ai_suggestion));
            throw new Exception('Failed to generate ai_suggestion');
          }
          else
          {
            $count++;
            $ai_suggestion = OpenAI::createNewArticleTitle($serp_url->title, $serp_url->description);
          }
        }

        $readability_content = ScrapeUrlBodyTask::handle($serp_url->url);

        if (is_null($readability_content)) {
            return self::saveAndReturnSerpProcessStatus($serp_url, -7);
        }

        $markdown = OpenAI::writeArticle($ai_suggestion->title, $readability_content, $ai_suggestion->article_type, 500, 800);

        if (is_empty($markdown)) {
            return self::saveAndReturnSerpProcessStatus($serp_url, -4);
        }

        $post = new Post;
        $post->title = $ai_suggestion->title;
        $post->type = $ai_suggestion->article_type;
        $post->short_title = $ai_suggestion->short_title;
        $post->main_keyword = $ai_suggestion->main_keyword;
        $post->keywords = $ai_suggestion->photo_keywords;
        $post->slug = str_slug($ai_suggestion->title);
        $post->excerpt = $ai_suggestion->description;
        $post->author_id = Author::find(1)->id;
        $post->featured = false;
        $post->featured_image = null;
        $post->body = $markdown;
        $post->status = 'draft';

        if ($post->save()) {
            $post_category = new PostCategory;
            $post_category->post_id = $post->id;
            $post_category->category_id = $serp_url->category->id;

            if ($post_category->save()) {
                GenerateArticleFeaturedImageJob::dispatch($post)->onQueue('default')->onConnection('default');

                return self::saveAndReturnSerpProcessStatus($serp_url, 1);
            } else {
                return self::saveAndReturnSerpProcessStatus($serp_url, -5);
            }
        }

        return self::saveAndReturnSerpProcessStatus($serp_url, -6);
    }

    private static function saveAndReturnSerpProcessStatus($serp_url, $process_status)
    {
        $serp_url->process_status = $process_status;
        $serp_url->save();

        return $serp_url->process_status;
    }
}
