<?php

namespace App\Observers;

use App\Models\ProductVariant;
use App\Services\ImageOptimizationService;

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

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

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