<?php

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

return new class extends Migration
{
    public function up(): void
    {
        DB::table('users')->whereNull('status')->update(['status' => 'active']);

        $specialistId = DB::table('roles')->where('name', 'specialist')->value('id');
        if (! $specialistId) {
            return;
        }

        $usersWithoutRoles = DB::table('users')
            ->leftJoin('role_user', 'users.id', '=', 'role_user.user_id')
            ->whereNull('role_user.user_id')
            ->select('users.id')
            ->get();

        foreach ($usersWithoutRoles as $user) {
            DB::table('role_user')->insert([
                'role_id' => $specialistId,
                'user_id' => $user->id,
                'created_at' => now(),
                'updated_at' => now(),
            ]);
        }
    }

    public function down(): void
    {
        // Data backfill only; leave user status and roles intact on rollback.
    }
};
