<?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\Gd\Driver;

class ImageCompressor
{
    private ImageManager $manager;

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

    /**
     * Compress an uploaded image and store it.
     * Dimensions are preserved; only file size is reduced via WebP encoding.
     *
     * @param  UploadedFile  $file       The uploaded file (Livewire TemporaryUploadedFile works too)
     * @param  string        $directory  Storage directory (e.g. 'gallery', 'posts')
     * @param  string        $disk       Storage disk (default: 'public')
     * @param  int           $quality    WebP quality 0–100 (default: 80)
     * @return string                    Stored file path relative to the disk root
     */
    public function compress(UploadedFile $file, string $directory, string $disk = 'public', int $quality = 80): string
    {
        return $this->compressFromContent($file->get(), $directory, $disk, $quality);
    }

    /**
     * Compress an image from raw content string or a remote URL and store it.
     *
     * @param  string|mixed  $content    Raw binary string or remote URL
     * @param  string        $directory  Storage directory (e.g. 'gallery', 'posts')
     * @param  string        $disk       Storage disk (default: 'public')
     * @param  int           $quality    WebP quality 0–100 (default: 80)
     * @return string                    Stored file path relative to the disk root
     */
    public function compressFromContent($content, string $directory, string $disk = 'public', int $quality = 80): string
    {
        $image = $this->manager->read($content);

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

        Storage::disk($disk)->put($path, (string) $image->toWebp($quality));

        return $path;
    }
}
