<?php

namespace App\Console\Commands\Network;

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

class AmazonSelfHealingCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'amazon:heal {start_days=0} {end_days=0} {--s|sandbox} {--c|confirmed} {--m|mute}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Amazon Self Healing Command';

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $startTime = microtime(true);
        $start_days = $this->argument('start_days');
        $end_days = $this->argument('end_days');
        $is_sandbox = $this->option('sandbox');
        $considerConfirmedOrders = $this->option('confirmed');
        $silentMode = $this->option('mute');

        if ($end_days > $start_days)
            die('end_days has to be less or equal start_days');

        $amazonNetworks = Network::where('controller', 'like', 'Amazon%')->get();
        foreach ($amazonNetworks as $amazonNetwork) {
            try {
                $selfHealingClass = "App\\Services\\AmazonSelfHealing\\{$amazonNetwork->controller}SelfHealing";
                $selfHealingService = new $selfHealingClass($amazonNetwork, $is_sandbox, $considerConfirmedOrders, $silentMode);
                $selfHealingService->fetchAndCompare(intval($start_days), intval($end_days));
            } catch (\Exception $exception) {
                if ($is_sandbox)
                    dump($exception->getMessage());

                Log::error('Amazon Self Healing Command Error', [
                    'message' => $exception->getMessage(),
                    'network' => $amazonNetwork->toArray(),
                    'start_days' => $start_days,
                    'end_days' => $end_days,
                    'exception' => $exception
                ]);
            }
        }
        $endTime = microtime(true);
        $executionTime = $endTime - $startTime;
        Log::channel("separated_file")->info("The Script".class_basename($this)."   Took : $executionTime");
        return;
    }
}
