<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Notifications\Slack;
use App\Services\Terminations\Retriever\RetrieverDataSyncService;
use Illuminate\Support\Facades\Notification;

class RetrieverDataSync extends Command
{

    protected $signature = 'RetrieverData:sync';
    protected $description = 'Sync the return device details from Retriever';

    public function __construct(protected RetrieverDataSyncService $dataSyncService)
    {
        parent::__construct();
    }

    /**
     * checks the API connection status, sends a notification if the connection is down,
     *  and then syncs retriever devices.
     *
     * @return string returns the total updated data count
     */
    public function handle()
    {
        // For Checking Connection status
        $connectionStatus = $this->dataSyncService->checkConnection();
        if (!$connectionStatus) {
            $this->sendNotification("FAILED! Retriever connection failed.");
            return $this->info("'FAILED! Retriever connection failed.");
        }

        $totalUpdated = $this->dataSyncService->syncRetrieverDevices();
        $this->sendNotification("Retriever sync completed successfully. Total updated data: " . $totalUpdated);

        return $this->info("Retriever sync completed successfully. Total updated data: " . $totalUpdated);
    }

    /**
     * Send Mail Notification
     *
     * @param string $message
     */
    public function sendNotification($message)
    {
        if (config('teqtivity-notification-mails.slack')) {
            Notification::route('slack', config('teqtivity-notification-mails.slack'))->notify(new Slack($message));
        }
    }
}
