<?php

namespace App\Console\Commands;

use App\Notifications\Slack;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use App\Services\AzureDirectoryService;
use Illuminate\Support\Facades\Notification;

class AzureDirectory extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'AzureDirectory:azuredirectory';
    
    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Synchronize employee data from Microsoft Azure Active Directory to the local database. 
                            This command will:
                            - Authenticate with Azure AD using configured credentials
                            - Fetch current employee directory data
                            - Update local records to match Azure AD data
                            - Send success/error notifications to Slack if configured';



    /**
     * Class constructor
     *
     * @param AzureDirectoryService $service The service for fetching and processing Azure Directory data
     */
    public function __construct(protected AzureDirectoryService $service)
    {
        $this->service  = $service;
        parent::__construct();
    }
    
    /**
     * Handles the execution of the AzureDirectory command:
     * - Fetches the current access token
     * - Authenticates with Azure AD using the token
     * - Synchronizes the Azure AD data with the local database
     * - Sends the result to Slack if configured
     * 
     * @return void
     */
    public function handle()
    {
        $token = $this->service->checkConnection();
        if (!$token) {
            $message = "Azure AD import error: Authentication failed. Token doesn't exist. Please check credentials.";
            return $this->handleResult(false, $message);
        }

        $count = $this->service->syncActiveDirectoryData();
        if ($count === false) {
            $message = "Azure AD import failed: Synchronization error occurred.";
            return $this->handleResult(false, $message);
        }

        $message = "Azure AD import successful: {$count} employees updated.";
        return $this->handleResult(true, $message);
    }

    /**
     * Handles the result of the AzureDirectory command:
     * - Logs the result to the single channel
     * - Sends the result to Slack if configured
     * - Returns the result as an info or error message
     *
     * @param bool $success
     * @param string $message
     *
     * @return void
     */
    protected function handleResult(bool $success, string $message)
    {
        $logMethod = $success ? 'info' : 'error';
        Log::channel('single')->$logMethod($message);

        $this->sendSlackNotification($success, $message);
        return $success ? $this->info($message) : $this->error($message);
    }

    /**
     * Sends a Slack notification if the Slack Webhook URL is configured.
     * 
     * @param bool $success Whether the operation was successful
     * @param string $message The message to be sent
     *
     * @return void
     */
     protected function sendSlackNotification(bool $success, string $message)
    {
        if (!config('teqtivity-notification-mails.slack')) {
            return;
        }

        $prefix = $success ? '✅ SUCCESS: ' : '❌ FAILED: ';
        $slackMessage = $prefix . $message;

        Notification::route('slack', config('teqtivity-notification-mails.slack'))->notify(new Slack($slackMessage));
    }
}
