<?php

namespace App\Console\Commands\Debug;

use App\Models\Address;
use Illuminate\Console\Command;

class AddressCheckRole extends Command
{
	/**
	 * The name and signature of the console command.
	 *
	 * @var string
	 */
	protected $signature = 'debug:address:check:role {--f|fix : Fix the role}';

	/**
	 * The console command description.
	 *
	 * @var string
	 */
	protected $description = 'Check address roles and optionally fix';

	/**
	 * Execute the console command.
	 */
	public function handle()
	{
		foreach (Address::withTrashed()->with(['zone.domain'])->cursor() as $o) {
			// Trim the role bit from role, since we now work out a role automatically.
			// @todo This doesnt work, because role_id returns back the overridden role, and thus would remove it
			if (($o->role & Address::NODE_ALL) === $o->role_id) {
				$o->role &= ~$o->role_id;

				if ((! $o->role) || ($o->role === Address::NODE_UNKNOWN))
					$o->role = NULL;

				if ($o->getDirty())
					if ($this->option('fix')) {
						$o->save();

					} else {
						$this->warn(sprintf('Not changing [%s](%s) from [%d] to [%d]',$o->ftn,$o->role_name,$o->getOriginal('role'),$o->role));
					}
			}
		}
	}
}