<?php

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

return new class extends Migration
{
    public function up(): void
    {
        $sites = DB::table('admin_sites')->orderBy('id')->get(['id', 'code']);

        foreach ($sites as $site) {
            $siteId = (int) $site->id;
            $code = (string) $site->code;
            $legacyCode = 'root-'.$code;

            $root = DB::table('agent_nodes')
                ->where('admin_site_id', $siteId)
                ->where('depth', 0)
                ->first(['id', 'code']);

            if ($root === null) {
                continue;
            }

            if ((string) $root->code === $legacyCode) {
                $conflict = DB::table('agent_nodes')
                    ->where('admin_site_id', $siteId)
                    ->where('code', $code)
                    ->where('id', '!=', (int) $root->id)
                    ->exists();
                if (! $conflict) {
                    DB::table('agent_nodes')->where('id', (int) $root->id)->update([
                        'code' => $code,
                        'updated_at' => now(),
                    ]);
                }
            }
        }
    }

    public function down(): void
    {
        $sites = DB::table('admin_sites')->orderBy('id')->get(['id', 'code']);

        foreach ($sites as $site) {
            $siteId = (int) $site->id;
            $code = (string) $site->code;

            DB::table('agent_nodes')
                ->where('admin_site_id', $siteId)
                ->where('depth', 0)
                ->where('code', $code)
                ->update([
                    'code' => 'root-'.$code,
                    'updated_at' => now(),
                ]);
        }
    }
};
