<?php

namespace App\Jobs;

use App\Service\ExternalApiService;
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 SendImagineJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public array $data = [];

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

    public function handle()
    {
        $data = $this->data;
        $key = app(TaskService::class)->getDiscordMessageKey($data['prompt']);
        Cache::set($key, ['prompt_task_id' => $data['prompt_id']], (60 * 60 * 24));
        // 处理图转图
        if ($data['type'] == TaskService::TYPE_IMG_TO_IMG) {
            $promptImg = json_decode(($data['prompt_img'] ?? ''));
            $data['prompt'] = ($promptImg[0] ?? '') . ' ' . $data['prompt'];
        }
        app(ExternalApiService::class)->imagine($data);
    }
}
