<?php

use App\Models\AdminRole;
use App\Support\SiteAdminDefaultRolePermissions;
use App\Support\SitePlatformRole;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;

return new class extends Migration
{
    public function up(): void
    {
        SiteAdminDefaultRolePermissions::ensurePlatformSiteAdminRole();
        $platformRoleId = SitePlatformRole::id();

        $legacyRoles = AdminRole::query()
            ->where('scope_type', AdminRole::SCOPE_SYSTEM)
            ->where('slug', 'like', 'site_admin_%')
            ->where('slug', '<>', SitePlatformRole::SLUG)
            ->get(['id', 'slug']);

        foreach ($legacyRoles as $legacy) {
            $bindings = DB::table('admin_user_site_roles')
                ->where('role_id', $legacy->id)
                ->get(['admin_user_id', 'site_id', 'granted_at']);

            foreach ($bindings as $binding) {
                DB::table('admin_user_site_roles')->updateOrInsert(
                    [
                        'admin_user_id' => (int) $binding->admin_user_id,
                        'site_id' => (int) $binding->site_id,
                        'role_id' => $platformRoleId,
                    ],
                    ['granted_at' => $binding->granted_at ?? now()],
                );
            }

            DB::table('admin_user_site_roles')->where('role_id', $legacy->id)->delete();
            AdminRole::query()->where('id', $legacy->id)->delete();
        }
    }

    public function down(): void
    {
        // 不回滚 per-site 角色拆分；仅保留平台 site_admin 角色。
    }
};
