<?php

namespace App\Notifications;

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

class SubscriptionStatusChanged extends Notification implements ShouldQueue
{
    use Queueable;

    public function __construct(
        public Subscription $subscription,
        public string $oldStatus,
        public string $newStatus,
        public ?string $reason = null
    ) {}

    public function via(object $notifiable): array
    {
        return ['database', 'mail'];
    }

    public function toMail(object $notifiable): MailMessage
    {
        $siteName = Setting::get('site_name', 'CoachPro');
        $planName = $this->subscription->plan->name ?? 'Tu plan';

        $mail = (new MailMessage)
            ->subject("Actualización de Suscripción - {$planName}")
            ->greeting("Hola {$notifiable->name},")
            ->line("Tu suscripción al plan **{$planName}** ha sido actualizada.")
            ->line("**Estado anterior:** " . $this->getStatusLabel($this->oldStatus))
            ->line("**Nuevo estado:** " . $this->getStatusLabel($this->newStatus));

        if ($this->reason) {
            $mail->line("**Motivo:** {$this->reason}");
        }

        $mail->action('Ver Mi Suscripción', route('coach.subscription.index'))
            ->salutation("Saludos,\nEl equipo de {$siteName}");

        return $mail;
    }

    public function toArray(object $notifiable): array
    {
        $planName = $this->subscription->plan->name ?? 'Tu plan';
        $icon = $this->getStatusIcon();

        return [
            'type' => 'subscription_status_changed',
            'subscription_id' => $this->subscription->id,
            'old_status' => $this->oldStatus,
            'new_status' => $this->newStatus,
            'plan_name' => $planName,
            'reason' => $this->reason,
            'message' => "{$icon} Suscripción {$planName}: {$this->getStatusLabel($this->newStatus)}",
            'title' => 'Estado de suscripción actualizado',
            'url' => route('coach.subscription.index'),
        ];
    }

    protected function getStatusLabel(string $status): string
    {
        return match($status) {
            'active' => 'Activa',
            'pending' => 'Pendiente',
            'expired' => 'Expirada',
            'cancelled' => 'Cancelada',
            'suspended' => 'Suspendida',
            default => ucfirst($status),
        };
    }

    protected function getStatusIcon(): string
    {
        return match($this->newStatus) {
            'active' => '✅',
            'cancelled' => '❌',
            'suspended' => '⚠️',
            'expired' => '⏰',
            default => 'ℹ️',
        };
    }
}
