<?php

namespace App\Services;

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

class ImageOptimizationService
{
    protected ImageManager $manager;

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

    /**
     * Generate WebP (80% quality) and thumbnail (300x300) for an uploaded image.
     * Returns ['webp' => path, 'thumbnail' => path] or null on failure.
     */
    public function processUploadedImage(string $imagePath, string $disk = 'public'): ?array
    {
        $fullPath = Storage::disk($disk)->path($imagePath);

        if (! file_exists($fullPath) || ! is_file($fullPath)) {
            return null;
        }

        try {
            $image = $this->manager->read($fullPath);
        } catch (\Throwable) {
            return null;
        }

        $info = pathinfo($imagePath);
        $dirname = $info['dirname'];
        $filename = $info['filename'];

        $webpPath = $dirname . '/' . $filename . '.webp';
        $thumbPath = $dirname . '/' . $filename . '_thumb.webp';

        $webpFull = Storage::disk($disk)->path($webpPath);
        $thumbFull = Storage::disk($disk)->path($thumbPath);

        // Ensure directory exists
        $webpDir = dirname($webpFull);
        if (! is_dir($webpDir)) {
            mkdir($webpDir, 0755, true);
        }

        try {
            // WebP full size at 80% quality
            $image->toWebp(quality: 80)->save($webpFull);

            // Thumbnail 300x300 (cover crop)
            $thumbImage = $this->manager->read($fullPath);
            $thumbImage->cover(300, 300);
            $thumbImage->toWebp(quality: 80)->save($thumbFull);

            return [
                'webp' => $webpPath,
                'thumbnail' => $thumbPath,
            ];
        } catch (\Throwable) {
            return null;
        }
    }
}
