<?php

namespace App\Console\Commands;

use App\Models\Product;
use App\Models\ProductVariant;
use App\Services\ImageOptimizationService;
use Illuminate\Console\Command;

class GenerateImageThumbnails extends Command
{
    protected $signature = 'images:generate-thumbnails
                            {--variants : Process product variants only}
                            {--products : Process products only}';

    protected $description = 'Generate WebP and thumbnail versions for existing product/variant images';

    public function handle(ImageOptimizationService $imageService): int
    {
        $processVariants = $this->option('variants') || ! $this->option('products');
        $processProducts = $this->option('products') || ! $this->option('variants');

        $processed = 0;

        if ($processVariants) {
            $variants = ProductVariant::whereNotNull('image')->whereNull('image_thumbnail')->get();
            foreach ($variants as $variant) {
                $result = $imageService->processUploadedImage($variant->image, 'public');
                if ($result) {
                    $variant->updateQuietly([
                        'image_webp' => $result['webp'],
                        'image_thumbnail' => $result['thumbnail'],
                    ]);
                    $processed++;
                }
            }
        }

        if ($processProducts) {
            $products = Product::whereNotNull('image')->whereNull('image_thumbnail')->get();
            foreach ($products as $product) {
                $result = $imageService->processUploadedImage($product->image, 'public');
                if ($result) {
                    $product->updateQuietly([
                        'image_webp' => $result['webp'],
                        'image_thumbnail' => $result['thumbnail'],
                    ]);
                    $processed++;
                }
            }
        }

        $this->info("Generated thumbnails for {$processed} images.");

        return self::SUCCESS;
    }
}
