<?php

namespace App\Notifications;

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

class AppointmentRequestNotification extends Notification implements ShouldQueue
{
    use Queueable;

    public $appointment;

    /**
     * Create a new notification instance.
     */
    public function __construct(Appointment $appointment)
    {
        $this->appointment = $appointment;
    }

    /**
     * Get the notification's delivery channels.
     *
     * @return array<int, string>
     */
    public function via(object $notifiable): array
    {
        $channels = ['database'];
        
        // Include mail channel - errors will be caught by try-catch in controllers
        // For development, set MAIL_MAILER=log in .env to avoid connection errors
        $channels[] = 'mail';
        
        return $channels;
    }

    /**
     * Get the mail representation of the notification.
     */
    public function toMail(object $notifiable): MailMessage
    {
        $appointmentDate = $this->appointment->appointment_date 
            ? $this->appointment->appointment_date->format('F d, Y \a\t g:i A')
            : 'Immediate consultation';
            
        $meetLink = $this->appointment->google_meet_link ?? 
            ($this->appointment->video_call_room_id 
                ? route('doctor.video-call', $this->appointment->id)
                : null);

        $mail = (new MailMessage)
            ->subject('New Appointment Request - ' . config('app.name'))
            ->greeting('Hello ' . $notifiable->doctor->full_name . ',')
            ->line('You have received a new appointment request.')
            ->line('**Patient:** ' . $this->appointment->patient->full_name)
            ->line('**Appointment Date:** ' . $appointmentDate)
            ->line('**Consultation Type:** ' . $this->appointment->consultation_type)
            ->line('**Branch:** ' . $this->appointment->branch->name);

        if ($meetLink) {
            $mail->action('Consult via Telemed', $meetLink);
        }

        $mail->action('View Appointment', route('doctor.appointments'))
            ->line('Thank you for using ' . config('app.name') . '!');

        return $mail;
    }

    /**
     * Get the array representation of the notification.
     *
     * @return array<string, mixed>
     */
    public function toArray(object $notifiable): array
    {
        return [
            'appointment_id' => $this->appointment->id,
            'patient_name' => $this->appointment->patient->full_name,
            'appointment_date' => $this->appointment->appointment_date?->toDateTimeString(),
            'consultation_type' => $this->appointment->consultation_type,
            'message' => 'New appointment request from ' . $this->appointment->patient->full_name,
        ];
    }
}
