<?php

namespace App\Console\Commands;

use App\Models\Commons\Menu;
use Illuminate\Console\Command;

class FixMenuUrlCommand extends Command
{
    protected $signature = 'menu:fix-url {name} {new-url} {--tenant=}';

    protected $description = '메뉴 URL 수정 (이름으로 검색)';

    public function handle(): int
    {
        $name = $this->argument('name');
        $newUrl = $this->argument('new-url');
        $tenantId = $this->option('tenant');

        $query = Menu::withoutGlobalScopes()->where('name', $name);

        if ($tenantId) {
            $query->where('tenant_id', $tenantId);
        }

        $menus = $query->get();

        if ($menus->isEmpty()) {
            $this->error("'{$name}' 메뉴를 찾을 수 없습니다.");

            return 1;
        }

        foreach ($menus as $menu) {
            $oldUrl = $menu->url;
            $menu->url = $newUrl;
            $menu->save();
            $this->info("수정: [T{$menu->tenant_id}] '{$menu->name}' URL: {$oldUrl} → {$newUrl}");
        }

        $this->info("{$menus->count()}건 수정 완료.");

        return 0;
    }
}
