<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;

class MsgraphSyncReport extends Notification
{
    use Queueable;

    protected $command;
    protected $success;
    protected $output;
    protected $duration;

    /**
     * Create a new notification instance.
     */
    public function __construct(string $command, bool $success, string $output, float $duration = null)
    {
        $this->command = $command;
        $this->success = $success;
        $this->output = $output;
        $this->duration = $duration;
    }

    /**
     * Get the notification's delivery channels.
     */
    public function via(object $notifiable): array
    {
        return ['mail'];
    }

    /**
     * Get the mail representation of the notification.
     */
    public function toMail(object $notifiable): MailMessage
    {
        $subject = $this->success
            ? "✅ Microsoft Graph Sync Successful - {$this->command}"
            : "❌ Microsoft Graph Sync Failed - {$this->command}";

        $greeting = $this->success
            ? "Microsoft Graph synchronization completed successfully!"
            : "Microsoft Graph synchronization failed!";

        $mail = (new MailMessage)
            ->subject($subject)
            ->greeting($greeting)
            ->line("**Command:** {$this->command}")
            ->line("**Status:** " . ($this->success ? 'Success ✅' : 'Failed ❌'));

        if ($this->duration) {
            $mail->line("**Duration:** " . number_format($this->duration, 2) . " seconds");
        }

        $mail->line("**Date:** " . now()->format('Y-m-d H:i:s T'))
             ->line('') // Empty line
             ->line('**Command Output:**')
             ->line('```')
             ->line($this->output)
             ->line('```');

        if (!$this->success) {
            $mail->line('')
                 ->line('⚠️ Please check the application logs for more detailed error information.')
                 ->action('View Application Logs', url('/admin'));
        }

        return $mail->line('')
                    ->line('This is an automated notification from the Microsoft Graph synchronization system.');
    }

    /**
     * Get the array representation of the notification.
     */
    public function toArray(object $notifiable): array
    {
        return [
            'command' => $this->command,
            'success' => $this->success,
            'output' => $this->output,
            'duration' => $this->duration,
        ];
    }
}
