<?php

namespace App\Services;

use App\Repos\SettingRepo;
use OpenAI;

class OpenaiService {
    public static function client() {
        $apiKey = SettingRepo::findByNameOrFail('openai_key');
        return OpenAI::client($apiKey->value);
    }

    public static function chat(string $prompt) {
        $client = self::client();
        $result = $client->chat()->create([
            'model' => 'gpt-4',
            'messages' => [
                ['role' => 'user', 'content' => $prompt],
            ],
        ]);
        return $result->choices[0]->message->content;
    }

    public static function createImage(string $prompt) {
        $client = self::client();
        $result = $client->images()->create([
            'model' => 'dall-e-3',
            'prompt' => $prompt,
            'n' => 1,
            'size' => '1024x1024',
            'response_format' => 'url',
        ]);
        $url = $result->data[0]->url;
        $file = file_get_contents($url);
        return StorageService::save($file, 'png');
    }
}
