<?php

namespace App\Notifications;

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

/**
 * Notification sent to customer when payment is received.
 */
class OrderPaid extends Notification implements ShouldQueue
{
    use Queueable;

    public function __construct(
        public Order $order
    ) {}

    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
    {
        return (new MailMessage)
            ->subject('Pago Recibido - Pedido #' . $this->order->order_number)
            ->greeting('¡Hola ' . $notifiable->name . '!')
            ->line('Hemos recibido tu pago correctamente.')
            ->line('')
            ->line('**Detalles del Pago:**')
            ->line('• Número de Pedido: ' . $this->order->order_number)
            ->line('• Monto: ' . $this->order->formatCurrency($this->order->total))
            ->line('• Método: ' . $this->getPaymentMethodLabel())
            ->line('• Fecha de Pago: ' . $this->order->paid_at->format('d/m/Y H:i'))
            ->when($this->order->transaction_id, function ($message) {
                return $message->line('• ID de Transacción: ' . $this->order->transaction_id);
            })
            ->line('')
            ->line('Tu pedido está ahora en proceso de preparación.')
            ->action('Ver Estado del Pedido', $this->getOrderUrl($notifiable))
            ->line('Te notificaremos cuando tu pedido sea enviado.')
            ->salutation('¡Gracias por tu compra!');
    }

    public function toArray(object $notifiable): array
    {
        return [
            'type' => 'order_paid',
            'order_id' => $this->order->id,
            'order_number' => $this->order->order_number,
            'total' => $this->order->total,
            'paid_at' => $this->order->paid_at?->toISOString(),
            'message' => "Pago recibido para el pedido #{$this->order->order_number}",
            'title' => 'Pago Confirmado',
            'url' => $this->getOrderUrl($notifiable),
        ];
    }

    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 getOrderUrl(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_paid';
    }
}
