<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::table('users', function (Blueprint $table) {
            $table->foreignId('role_id')
                ->nullable()
                ->after('password')
                ->constrained()
                ->restrictOnDelete();
        });

        $now = now();

        foreach ([
            [
                'name' => 'Admin',
                'slug' => 'admin',
                'description' => 'Full access to platform users, roles, and permissions.',
            ],
            [
                'name' => 'Manager',
                'slug' => 'manager',
                'description' => 'Operational access to platform users without role administration.',
            ],
        ] as $role) {
            DB::table('roles')->updateOrInsert(
                ['slug' => $role['slug']],
                [
                    ...$role,
                    'created_at' => $now,
                    'updated_at' => $now,
                ],
            );
        }

        $roleIds = DB::table('roles')->pluck('id', 'slug');

        foreach (DB::table('users')->orderBy('id')->get() as $user) {
            $slug = $user->role === 'admin' ? 'admin' : 'manager';

            DB::table('users')->where('id', $user->id)->update([
                'role_id' => $roleIds[$slug],
            ]);
        }

        Schema::table('users', function (Blueprint $table) {
            $table->dropIndex(['role']);
            $table->dropColumn('role');
        });

        Schema::table('users', function (Blueprint $table) {
            $table->unsignedBigInteger('role_id')->nullable(false)->change();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('users', function (Blueprint $table) {
            $table->string('role')->default('manager')->after('password')->index();
        });

        $roleSlugs = DB::table('roles')->pluck('slug', 'id');

        foreach (DB::table('users')->orderBy('id')->get() as $user) {
            DB::table('users')->where('id', $user->id)->update([
                'role' => $roleSlugs[$user->role_id] ?? 'manager',
            ]);
        }

        Schema::table('users', function (Blueprint $table) {
            $table->dropConstrainedForeignId('role_id');
        });
    }
};
