<?php

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

return new class extends Migration
{
    public function up(): void
    {
        if (! Schema::hasTable('stores')) {
            Schema::create('stores', function (Blueprint $table) {
                $table->id();

                $table->foreignId('store_group_id')
                    ->constrained('store_groups')
                    ->cascadeOnUpdate()
                    ->restrictOnDelete();

                $table->string('name');
                $table->string('legal_id')->nullable();
                $table->boolean('is_active')->default(true);

                $table->timestamps();
            });

            return;
        }

        Schema::table('stores', function (Blueprint $table) {
            if (! Schema::hasColumn('stores', 'store_group_id')) {
                $table->foreignId('store_group_id')
                    ->nullable()
                    ->after('id');
            }

            if (! Schema::hasColumn('stores', 'name')) {
                $table->string('name')->after('store_group_id');
            }

            if (! Schema::hasColumn('stores', 'legal_id')) {
                $table->string('legal_id')->nullable()->after('name');
            }

            if (! Schema::hasColumn('stores', 'is_active')) {
                $table->boolean('is_active')->default(true)->after('legal_id');
            }

            if (! Schema::hasColumn('stores', 'created_at')) {
                $table->timestamps();
            }
        });
    }

    public function down(): void
    {
        // Intencionalmente no hacemos drop para evitar pérdida de datos en entornos existentes.
    }
};
