<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('product_attributes', function (Blueprint $table) {
            $table->id();
            $table->string('name')->unique();
            $table->timestamps();
        });

        Schema::create('product_attribute_values', function (Blueprint $table) {
            $table->id();
            $table->foreignId('product_attribute_id')->constrained('product_attributes')->cascadeOnDelete();
            $table->string('value');
            $table->timestamps();
            $table->unique(['product_attribute_id', 'value']);
        });

        // Seed default attributes
        $now = now();
        
        $sizeId = DB::table('product_attributes')->insertGetId([
            'name' => 'Size',
            'created_at' => $now,
            'updated_at' => $now,
        ]);

        $colorId = DB::table('product_attributes')->insertGetId([
            'name' => 'Color',
            'created_at' => $now,
            'updated_at' => $now,
        ]);

        $sizes = ['S', 'M', 'L', 'XL', 'XXL'];
        foreach ($sizes as $size) {
            DB::table('product_attribute_values')->insert([
                'product_attribute_id' => $sizeId,
                'value' => $size,
                'created_at' => $now,
                'updated_at' => $now,
            ]);
        }

        $colors = ['Black', 'White', 'Red', 'Blue', 'Grey'];
        foreach ($colors as $color) {
            DB::table('product_attribute_values')->insert([
                'product_attribute_id' => $colorId,
                'value' => $color,
                'created_at' => $now,
                'updated_at' => $now,
            ]);
        }
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('product_attribute_values');
        Schema::dropIfExists('product_attributes');
    }
};
