<?php

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

return new class extends Migration
{
    public function up(): void
    {
        $legacyId = DB::table('roles')->where('name', 'team_member')->value('id');
        $specialistId = DB::table('roles')->where('name', 'specialist')->value('id');

        if (! $legacyId || ! $specialistId) {
            return;
        }

        $legacyUsers = DB::table('role_user')->where('role_id', $legacyId)->get();
        foreach ($legacyUsers as $legacyUser) {
            DB::table('role_user')->updateOrInsert(
                ['role_id' => $specialistId, 'user_id' => $legacyUser->user_id],
                ['created_at' => $legacyUser->created_at ?? now(), 'updated_at' => now()]
            );
        }

        DB::table('role_user')->where('role_id', $legacyId)->delete();
        DB::table('permission_role')->where('role_id', $legacyId)->delete();
        DB::table('roles')->where('id', $legacyId)->delete();
    }

    public function down(): void
    {
        DB::table('roles')->updateOrInsert(
            ['name' => 'team_member'],
            [
                'display_name' => 'عضو تیم',
                'description' => 'دسترسی پایه برای انجام وظایف محوله',
                'guard_name' => 'web',
                'created_at' => now(),
                'updated_at' => now(),
            ]
        );
    }
};
