<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::table('users', function (Blueprint $table) {
            // 1. Corregir tipo de dato para 'type' (boolean en lugar de boolval)
            $table->unsignedSmallInteger('user_type')->default(false)->after('remember_token');
            
            // 2. Agregar company_id como nullable con constrained correcto
            $table->foreignId('company_id')
                  ->nullable()
                  ->after('user_type')
                  ->constrained('companies'); // Especificar tabla explícitamente
        });

        Schema::table('projects', function (Blueprint $table) {
            $table->foreignId('company_id')
                  ->constrained('companies');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('users', function (Blueprint $table) {
            // 5. Eliminar restricción de clave foránea primero
            $table->dropForeign(['company_id']);
            
            // 6. Eliminar columnas en orden inverso
            $table->dropColumn('company_id');
            $table->dropColumn('user_type');
        });

        Schema::table('projects', function (Blueprint $table) {
            // 7. Eliminar restricción antes de la columna
            $table->dropForeign(['company_id']);
            $table->dropColumn('company_id');
        });
    }
};
