<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;

return new class extends Migration
{
    public function up(): void
    {
        Schema::table('products', function (Blueprint $table) {
            $table->string('slug')->nullable()->unique()->after('name');
            $table->string('code', 50)->nullable()->unique()->after('slug');
        });

        $products = DB::table('products')->orderBy('id')->get(['id', 'name']);
        foreach ($products as $product) {
            $base = Str::slug($product->name) ?: 'product';
            $slug = $base . '-' . $product->id;
            $code = 'RV-' . str_pad((string) $product->id, 4, '0', STR_PAD_LEFT);

            DB::table('products')->where('id', $product->id)->update([
                'slug' => $slug,
                'code' => $code,
            ]);
        }
    }

    public function down(): void
    {
        Schema::table('products', function (Blueprint $table) {
            $table->dropColumn(['slug', 'code']);
        });
    }
};
