<?php

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

/**
 * 修正代理主账号 admin_users.status 与 agent_nodes.status 语义不一致的历史数据。
 *
 * admin_users: 0=可登录, 1=禁用
 * agent_nodes: 1=启用, 0=停用
 */
return new class extends Migration
{
    public function up(): void
    {
        $now = now();

        $enabledUserIds = DB::table('admin_user_agents as aua')
            ->join('agent_nodes as an', 'an.id', '=', 'aua.agent_node_id')
            ->join('admin_users as au', 'au.id', '=', 'aua.admin_user_id')
            ->where('aua.is_primary', true)
            ->where('an.status', 1)
            ->where('au.status', 1)
            ->pluck('au.id');

        if ($enabledUserIds->isNotEmpty()) {
            DB::table('admin_users')
                ->whereIn('id', $enabledUserIds->all())
                ->update(['status' => 0, 'updated_at' => $now]);
        }

        $disabledUserIds = DB::table('admin_user_agents as aua')
            ->join('agent_nodes as an', 'an.id', '=', 'aua.agent_node_id')
            ->join('admin_users as au', 'au.id', '=', 'aua.admin_user_id')
            ->where('aua.is_primary', true)
            ->where('an.status', 0)
            ->where('au.status', 0)
            ->pluck('au.id');

        if ($disabledUserIds->isNotEmpty()) {
            DB::table('admin_users')
                ->whereIn('id', $disabledUserIds->all())
                ->update(['status' => 1, 'updated_at' => $now]);
        }
    }

    public function down(): void
    {
        // 不可逆：无法可靠还原误写前的 admin_users.status
    }
};
