<?php

namespace App\Services;

use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Intervention\Image\Drivers\Gd\Driver;
use Intervention\Image\ImageManager;

class ImageService
{
    private ImageManager $manager;

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

    /**
     * Compress, resize and store an uploaded image.
     *
     * Images are scaled down to fit within 1200×1200 px (aspect ratio preserved,
     * never upscaled) and encoded as JPEG at 82 % quality.
     *
     * @return string  Storage-relative path to the saved file (e.g. "products/uuid.jpg")
     */
    public function compressAndStore(UploadedFile $file, string $directory, string $disk = 'public'): string
    {
        $image = $this->manager->read($file->getPathname());

        // Scale down only — never enlarge smaller images
        $image->scaleDown(width: 1200, height: 1200);

        $encoded = $image->toJpeg(quality: 82);

        $path = $directory . '/' . Str::uuid() . '.jpg';
        Storage::disk($disk)->put($path, (string) $encoded);

        return $path;
    }
}
