<?php

namespace App\Console\Commands\Network;

use App\Console\Commands\BaseCommand;
use Log;
use Illuminate\Support\Facades\Notification;
use App\Notifications\SlackNotification;
use Carbon\Carbon;

use App\Models\Goliath\GoliathAppliance;
use App\Models\ApiEvent;

class GoliathMonitorAgent extends BaseCommand
{

    protected $signature = 'goliath:monitor-agent';

    protected $description = 'Monitors goliath appliances to see whether the agents are active.';

    public function handle()
    {
        try {
            $appliances = GoliathAppliance::leftJoin('goliath_metro', 'goliath_metro.id', '=', 'goliath_appliances.metro_id')
                ->leftJoin('goliath_subregions', 'goliath_subregions.id', '=', 'goliath_appliances.subregion_id')
                ->leftJoin('goliath_regions', 'goliath_regions.id', '=', 'goliath_appliances.region_id')
                ->select('goliath_appliances.id', 'address', 'goliath_metro.name as metro', 'goliath_subregions.name as subregion', 'goliath_regions.name as region')
                ->where('goliath_appliances.id', '!=', 18)
                ->get();

            $relevant_events = ApiEvent::where([
                    ['created_at', '>', Carbon::now()->subMinute()],
                    ['description', '=', 'Method: GET'],
                    ['payload', 'LIKE', '{"appliance_id":"%'],
                    ['route', 'LIKE', 'api/goliath/data%']
                ])
                ->whereIn('ip', $appliances->pluck('address'))
                ->get();

            $missing_callouts = [];

            foreach($appliances as $appliance) {
                if(count($relevant_events->where('ip', '=', $appliance->address)) === 0) {
                    $missing_callouts[] = $appliance;
                }
            }

            foreach($missing_callouts as $missing) {
                Notification::route('slack', config('creatia.webhook.appliance'))->notify(new SlackNotification(
                    "The agent for an appliance of ID: $missing->id has not been seen in the past minute. Please investigate. Facility: $missing->metro, subregion: $missing->subregion, region: $missing->region, address: $missing->address"
                ));
            }
        }
        catch(\Throwable $e) {}

        return 0;
    }
}