<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Exception;
use Illuminate\Support\Facades\Notification;
use App\Notifications\Integrations\SlackSyncNotification;
use Illuminate\Support\Facades\Log;
use App\Services\SoftwareLicense\ImportedAssets\SlackService;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Sync the slack info and member list';

    private $service;
    /**
     * Create a new command instance.
     *
     * @return void
     */

    public function __construct(SlackService $service)
    {
        parent::__construct();
        $this->name = 'Slack';
        $this->service = $service;
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        try {
            $credentials = $this->service->getCredentials();

            if (!$credentials) {
                $this->info(json_encode([
                    'status'  => 'error',
                    'message' => $this->name . ' credentials are not found.'
                ]));

                return;
            }

            $assetDetails = $this->service->getLicenseData();

            if (!$assetDetails) {
                $this->info(json_encode([
                    'status'  => 'error',
                    'message' => $this->name . ' asset not created yet.'
                ]));

                return;
            }

            if (!$this->service->checkConnection($credentials)) {
                $connectionStatus = $this->service->setConnection();

                if ($connectionStatus !== true) {
                    $this->info(json_encode([
                        'status'  => 'error',
                        'message' => $this->name . ' credentials are invalid.'
                    ]));

                    return;
                }
            }

            $status = 'error';
            $message = 'An error occured with ' . $this->name . '  sync';
            $syncActionResponseStatus = $this->syncActions($credentials, $assetDetails);
            
            if ($syncActionResponseStatus['status']) {
                $status = 'success';
                $message = $this->name . ' sync completed successfully';
                $this->sendNotification(true);
            }


            $this->info(json_encode([
                'status'  => $status,
                'message' => $message
            ]));


            return;
        } catch (Exception $e) {
            Log::channel('daily')->info($this->name . " sync error: " . $e->getMessage());
            $this->sendNotification(false);
            $this->info(json_encode([
                'status'  => 'success',
                'message' => $this->name . ' sync failed.'
            ]));

            return;
        }
    }

    /**
     * Software aseet api sync actions
     * 
     * @param object $credentials
     * @param object $assetDetails
     * 
     * @return array 
     */
    private function syncActions($credentials, $assetDetails)
    {
        $status = true;
        $message = $this->name . ' sync completed successfully';
        $updateLicencePurchasedCountStatus = $this->service->updateLicencePurchasedCount($credentials, $assetDetails);


        if (!$updateLicencePurchasedCountStatus) {
            $status = false;
            $message = 'An error occured with update on licence purchased Count';
        }

        $createSoftwareAssetMembersStatus = $this->service->createMembers($credentials);

        if (!$createSoftwareAssetMembersStatus) {
            $status = false;
            $message = 'An error occured with adding ' . $this->name . ' members';
        }

        $softwareAssetMemberListSyncStatus = $this->service->softwareAssetMemberListSync($assetDetails);

        if (!$softwareAssetMemberListSyncStatus) {
            $status = false;
            $message = 'An error occured with ' . $this->name . ' member list sync';
        }

        $updateSoftwareOwnerStatus = $this->service->updateSoftwareAssetOwner($assetDetails);

        if (!$updateSoftwareOwnerStatus) {
            $status = false;
            $message = 'An error occured with update of ' . $this->name . ' owner';
        }


        $updateLicensesUsedCountStatus = $this->service->updateLicensesUsedCount($assetDetails);

        if (!$updateLicensesUsedCountStatus) {
            $status = false;
            $message = 'An error occured with update of ' . $this->name . ' used license count';
        }

        return ['status' => $status, 'message' => $message];
    }




    /**
     *  It sends a notification to a Slack channel using the Slack webhook URL
     * 
     * @param bool status true or false
     */
    public function sendNotification(bool $status)
    {
        Notification::route('slack', config('teqtivity-notification-mails.slack'))->notify(new SlackSyncNotification($status));
    }
}
