<?php

namespace App\Jobs;

use App\Models\PromptTask;
use App\Service\TaskService;
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\Cache;

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

    public array $data = [];

    public function __construct(array $data = [])
    {
        $this->queue = "{send-discord-message}";
        $this->data = $data;
    }

    public function handle()
    {
        $data = $this->data;
        $content = $data['message_content'] ?? '';
        preg_match('/\*\*<(.*)> (.*)\*\*/', $content, $matches);
        if (blank($matches)) {
            preg_match('/\*\*(.*)\*\*/', $content, $matches);
            $content = $matches[1] ?? '';
        } else {
            $content = $matches[2] ?? '';
        }

        if (isset($content) && filled($content)) {
            $key = app(TaskService::class)->getDiscordMessageKey($content);
            $cachePrompt = Cache::get($key);
            if (!empty($cachePrompt)) {
                $updateData = [
                    'result_img_status' => TaskService::STATUS_SUCCESS,
                    'result_img' => $data['attachment_url'],
                ];
                PromptTask::where('id', $cachePrompt['prompt_task_id'])
                    ->update($updateData);
                Cache::forget($key);
            }
        }
    }
}
