<?php

namespace App\Console\Commands\Network;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Yajny\Member\Models\Network;

class ValidateLinksCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'network:validate_links';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Validate network Links';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $startTime = microtime(true);
        $networks = Network::where('enabled', 1)->where('type', 'pull')->get();
        foreach ($networks as $network) {
            try {
                if ($network->controller && class_exists('\App\Http\Controllers\Network\\' . $network->controller)) {
                    $networkCtrl = app()->make('\App\Http\Controllers\Network\\' . $network->controller, compact('network'));
                    $networkCtrl->validateLinks();
                }
            } catch (\Exception $exception) {
                Log::error('Failed to validate links', [
                    'exception' => $exception,
                    'network' => $network->toArray()
                ]);
            }
        }
        $endTime = microtime(true);
        $executionTime = $endTime - $startTime;
        Log::channel("separated_file")->info("The Script".class_basename($this)."   Took : $executionTime");
    }
}
