<?php

namespace App\Observers;

use App\Models\Product;
use App\Services\ImageOptimizationService;

class ProductImageObserver
{
    public function __construct(
        protected ImageOptimizationService $imageService
    ) {}

    public function saved(Product $product): void
    {
        if (! $product->wasChanged('image')) {
            return;
        }
        if (! $product->image) {
            $product->updateQuietly([
                'image_webp' => null,
                'image_thumbnail' => null,
            ]);
            return;
        }

        $result = $this->imageService->processUploadedImage($product->image, 'public');
        if ($result) {
            $product->updateQuietly([
                'image_webp' => $result['webp'],
                'image_thumbnail' => $result['thumbnail'],
            ]);
        }
    }
}
