<?php

namespace Database\Migrations;

use Illuminate\Database\Migrations\Migration;
use App\Models\Product;

return new class extends Migration
{
    public function up(): void
    {
        // Synchroniser les images JSON vers la colonne image
        $products = Product::whereNotNull('images')->get();
        
        foreach ($products as $product) {
            try {
                $images = json_decode($product->images, true);
                if (is_array($images) && !empty($images)) {
                    // Prendre la première image du tableau
                    $firstImage = $images[0];
                    if (is_array($firstImage) && isset($firstImage['path'])) {
                        $product->image = $firstImage['path'];
                    } elseif (is_string($firstImage)) {
                        $product->image = $firstImage;
                    }
                    
                    // Utiliser la première image comme thumbnail
                    if (!$product->thumbnail) {
                        $product->thumbnail = $product->image;
                    }
                    
                    $product->save();
                }
            } catch (\Exception $e) {
                // Skip si erreur sur cet enregistrement
                continue;
            }
        }
    }

    public function down(): void
    {
        // Rollback - vider les colonnes image et thumbnail
        Product::query()->update([
            'image' => null,
            'thumbnail' => null,
        ]);
    }
};
