<?php

namespace App\Services;

use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Intervention\Image\ImageManager;
use Intervention\Image\Drivers\Imagick\Driver;
use Intervention\Image\Interfaces\ImageInterface;

class ImageService
{
    private ImageManager $manager;

    public function __construct()
    {
        $this->manager = new ImageManager(new Driver());
    }

    public const PRESET_AVATAR = 'avatar';
    public const PRESET_CATEGORY = 'category';
    public const PRESET_LISTING = 'listing';
    public const PRESET_REVIEW = 'review';
    public const PRESET_POST = 'post';

    private const PRESETS = [
        self::PRESET_AVATAR => [
            'max_width' => 400,
            'max_height' => 400,
            'quality' => 80,
        ],
        self::PRESET_CATEGORY => [
            'max_width' => 800,
            'max_height' => 800,
            'quality' => 80,
        ],
        self::PRESET_LISTING => [
            'max_width' => 1920,
            'max_height' => 1080,
            'quality' => 80,
        ],
        self::PRESET_REVIEW => [
            'max_width' => 1200,
            'max_height' => 1200,
            'quality' => 80,
        ],
        self::PRESET_POST => [
            'max_width' => 1080,
            'max_height' => 1080,
            'quality' => 80,
        ],
    ];

    /**
     * Görseli sıkıştır, yeniden boyutlandır ve WebP olarak kaydet.
     */
    public function compress(UploadedFile $file, string $directory, string $preset): string
    {
        $config = self::PRESETS[$preset] ?? self::PRESETS[self::PRESET_LISTING];

        $image = $this->manager->read($file->getRealPath());

        $image = $this->scaleDown($image, $config['max_width'], $config['max_height']);

        $filename = Str::uuid() . '.webp';
        $path = trim($directory, '/') . '/' . $filename;

        $encoded = $image->toWebp($config['quality']);

        Storage::disk('public')->put($path, (string) $encoded);

        return $path;
    }

    private function scaleDown(ImageInterface $image, int $maxWidth, int $maxHeight): ImageInterface
    {
        $width = $image->width();
        $height = $image->height();

        if ($width <= $maxWidth && $height <= $maxHeight) {
            return $image;
        }

        return $image->scaleDown($maxWidth, $maxHeight);
    }
}
