<?php

namespace App\Services\AI;

use App\Contracts\ImageCreativeGenerator;
use App\DTOs\CreativeBrief;
use Laravel\Ai\Image;

class LaravelAiImageGenerator implements ImageCreativeGenerator
{
    public function generate(CreativeBrief $brief, string $ratio, ?string $style = null): string
    {
        $prompt = $this->buildPrompt($brief, $style);

        $path = Image::of($prompt)
            ->size($ratio)
            ->quality('high')
            ->generate()
            ->storePublicly('creatives/images', 'public');

        if ($path === false) {
            throw new \RuntimeException('Failed to store the generated image.');
        }

        return $path;
    }

    private function buildPrompt(CreativeBrief $brief, ?string $style): string
    {
        $styleLine = $style ? "Visual style: {$style}." : '';

        return trim(sprintf(
            "A high-quality advertising image for %s. Benefits to convey: %s. %s Messaging tone: %s. Include a clear sense of the call to action: %s.",
            $brief->productName,
            implode(', ', $brief->benefits),
            $styleLine,
            $brief->messaging,
            $brief->cta,
        ));
    }
}
