<?php

namespace App\Notifications;

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

/**
 * Notification sent to customer when payment fails.
 */
class OrderPaymentFailed extends Notification implements ShouldQueue
{
    use Queueable;

    public function __construct(
        public Order $order,
        public ?string $reason = null
    ) {}

    public function via(object $notifiable): array
    {
        // Database first to ensure in-app notification is saved even if email fails
        return ['database', 'mail'];
    }

    public function toMail(object $notifiable): MailMessage
    {
        $message = (new MailMessage)
            ->subject('❌ Error en el Pago - Pedido #' . $this->order->order_number)
            ->greeting('¡Hola ' . $notifiable->name . '!')
            ->line('Lamentamos informarte que hubo un problema al procesar el pago de tu pedido.')
            ->line('')
            ->line('**Detalles del Pedido:**')
            ->line('• Número de Pedido: ' . $this->order->order_number)
            ->line('• Total: ' . $this->order->formatCurrency($this->order->total))
            ->line('• Método de Pago: ' . $this->getPaymentMethodLabel());

        if ($this->reason) {
            $message->line('')
                ->line('**Motivo:** ' . $this->reason);
        }

        return $message
            ->line('')
            ->line('Por favor, intenta realizar el pago nuevamente o utiliza un método de pago diferente.')
            ->action('Reintentar Pago', $this->getPaymentUrl($notifiable))
            ->line('Si necesitas ayuda, no dudes en contactarnos.')
            ->salutation('¡Gracias por tu paciencia!');
    }

    public function toArray(object $notifiable): array
    {
        return [
            'type' => 'order_payment_failed',
            'order_id' => $this->order->id,
            'order_number' => $this->order->order_number,
            'total' => $this->order->total,
            'reason' => $this->reason,
            'message' => "Error al procesar el pago del pedido #{$this->order->order_number}",
            'title' => 'Pago Fallido',
            'url' => $this->getPaymentUrl($notifiable),
            'icon' => 'x-circle',
            'priority' => 'high',
        ];
    }

    protected function getPaymentMethodLabel(): string
    {
        $methods = [
            'cash' => 'Pago contra entrega',
            'stripe' => 'Tarjeta de crédito/débito',
            'paypal' => 'PayPal',
            'transfer' => 'Transferencia bancaria',
        ];

        return $methods[$this->order->payment_method] ?? $this->order->payment_method;
    }

    protected function getPaymentUrl(object $notifiable): string
    {
        $prefix = match($notifiable->role) {
            'admin' => 'admin',
            'coach' => 'coach',
            default => 'client',
        };

        return route("{$prefix}.store.orders.show", $this->order->id);
    }

    public function databaseType(object $notifiable): string
    {
        return 'order_payment_failed';
    }
}
