<?php

namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Artisan;
use App\Notifications\MsgraphSyncReport;
use App\Models\EmailRecipient;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        //
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        // Microsoft Graph SMART synchronization - runs daily at 1:00 AM
        // This processes only the specific changes tracked in the database
        // Removed withoutOverlapping() due to cache permissions issues on production server
        $schedule->command('msgraph:smart-sync --sync-all --email-report=christian.freitas@eae.pt,m.cubelic@energytraderseurope.org,alex@eae.pt,antonio@eae.pt')
                 ->dailyAt('01:00')
                 ->name('msgraph-smart-sync-morning');

        // Microsoft Graph SMART synchronization - runs daily at 13:00 PM
        // Removed withoutOverlapping() due to cache permissions issues on production server
        $schedule->command('msgraph:smart-sync --sync-all --email-report=christian.freitas@eae.pt,m.cubelic@energytraderseurope.org,alex@eae.pt,antonio@eae.pt')
                 ->dailyAt('13:00')
                 ->name('msgraph-smart-sync-afternoon');

        // HubSpot synchronization - runs daily at 03:00 AM and 15:00 PM
        // Syncs committee, workgroup, and member users to HubSpot contact lists
        $hubspotEmailRecipients = config('hubspot.email_report.recipients', '');
        if (config('hubspot.sync_enabled', false)) {
            // Build command with properly quoted email recipients
            $hubspotCommand = 'hubspot:sync';
            if (!empty($hubspotEmailRecipients)) {
                // Wrap in quotes to preserve commas as a single argument value
                $hubspotCommand .= ' --email-report="' . $hubspotEmailRecipients . '"';
            }

            // Morning sync at 03:00
            $schedule->command($hubspotCommand)
                     ->dailyAt('03:00')
                     ->name('hubspot-sync-morning');

            // Afternoon sync at 15:00
            $schedule->command($hubspotCommand)
                     ->dailyAt('15:00')
                     ->name('hubspot-sync-afternoon');
        }

        // Microsoft Graph NEW USERS synchronization - runs daily at 2:00 AM
        // This processes only new users (is_new = 1) with permanent folder deletion
        // $schedule->call(function () {
        //     $this->runMsgraphCommandWithEmail('msgraph:sync --all', 'Microsoft Graph New Users Sync');
        // })->dailyAt('02:00')
        //   ->name('msgraph-new-users-sync')
        //   ->withoutOverlapping();
    }

    /**
     * Run a Microsoft Graph command and send email report
     */
    private function runMsgraphCommandWithEmail(string $command, string $description)
    {
        $emailAddress = env('MSGRAPH_SYNC_EMAIL_LOG');

        if (!$emailAddress) {
            Log::warning("MSGRAPH_SYNC_EMAIL_LOG not configured, skipping email notification for: {$command}");
            // Fall back to just running the command without email
            Artisan::call($command);
            return;
        }

        $startTime = microtime(true);
        $success = false;
        $output = '';

        try {
            Log::info("Starting {$description}: {$command}");

            // Capture command output
            $exitCode = Artisan::call($command);
            $output = Artisan::output();

            $success = ($exitCode === 0);
            $duration = microtime(true) - $startTime;

            if ($success) {
                Log::info("{$description} completed successfully", [
                    'command' => $command,
                    'duration' => $duration,
                    'exit_code' => $exitCode
                ]);
            } else {
                Log::error("{$description} failed", [
                    'command' => $command,
                    'duration' => $duration,
                    'exit_code' => $exitCode,
                    'output' => $output
                ]);
            }

        } catch (\Exception $e) {
            $duration = microtime(true) - $startTime;
            $output = "Exception occurred: " . $e->getMessage() . "\n\nStack trace:\n" . $e->getTraceAsString();

            Log::error("{$description} threw exception", [
                'command' => $command,
                'duration' => $duration,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
        }

        // Send email notification
        try {
            $recipient = new EmailRecipient($emailAddress, 'Microsoft Graph Admin');
            $recipient->notify(new MsgraphSyncReport($command, $success, $output, $duration ?? null));

            Log::info("Email notification sent for {$description}", [
                'recipient' => $emailAddress,
                'success' => $success
            ]);

        } catch (\Exception $e) {
            Log::error("Failed to send email notification for {$description}", [
                'recipient' => $emailAddress,
                'error' => $e->getMessage()
            ]);
        }
    }

    /**
     * Register the commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        $this->load(__DIR__.'/Commands');

        require base_path('routes/console.php');
    }
}
