<?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 their order is confirmed.
 */
class OrderConfirmed 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
    {
        $itemsList = $this->order->items->map(function ($item) {
            return "• {$item->product_name} x{$item->quantity} - " . $this->order->formatCurrency($item->total);
        })->join("\n");

        return (new MailMessage)
            ->subject('Confirmación de Pedido #' . $this->order->order_number)
            ->greeting('¡Gracias por tu compra, ' . $notifiable->name . '!')
            ->line('Tu pedido ha sido recibido y está siendo procesado.')
            ->line('')
            ->line('**Número de Pedido:** ' . $this->order->order_number)
            ->line('**Fecha:** ' . $this->order->created_at->format('d/m/Y H:i'))
            ->line('')
            ->line('**Productos:**')
            ->line($itemsList)
            ->line('')
            ->line('**Subtotal:** ' . $this->order->formatCurrency($this->order->subtotal))
            ->when($this->order->discount > 0, function ($message) {
                return $message->line('**Descuento:** -' . $this->order->formatCurrency($this->order->discount));
            })
            ->when($this->order->shipping > 0, function ($message) {
                return $message->line('**Envío:** ' . $this->order->formatCurrency($this->order->shipping));
            })
            ->line('**Total:** ' . $this->order->formatCurrency($this->order->total))
            ->line('')
            ->line('**Método de Pago:** ' . $this->getPaymentMethodLabel())
            ->action('Ver Mi Pedido', $this->getOrderUrl($notifiable))
            ->line('Te notificaremos cuando tu pedido sea enviado.')
            ->salutation('Gracias por confiar en nosotros.');
    }

    public function toArray(object $notifiable): array
    {
        return [
            'type' => 'order_confirmed',
            'order_id' => $this->order->id,
            'order_number' => $this->order->order_number,
            'total' => $this->order->total,
            'items_count' => $this->order->items->count(),
            'message' => "Tu pedido #{$this->order->order_number} ha sido confirmado",
            'title' => 'Pedido 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_confirmed';
    }
}
