<?php

namespace App\Notifications;

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

class TierUpgradedNotification extends Notification implements ShouldQueue
{
    use Queueable;

    public function __construct(
        public string $previousTierName,
        public string $newTierName,
    ) {}

    public function via(object $notifiable): array
    {
        if (! Setting::get('notify_tier_upgraded', true)) {
            return [];
        }
        return ['mail'];
    }

    public function toMail(User $notifiable): MailMessage
    {
        $this->logNotification($notifiable);

        return (new MailMessage)
            ->subject("Congratulations! You've been upgraded to {$this->newTierName}")
            ->greeting("Congratulations, {$notifiable->first_name}! 🎉")
            ->line("We're thrilled to let you know that you've been upgraded from **{$this->previousTierName}** to **{$this->newTierName}**!")
            ->line('This means you now have access to even more exclusive benefits and privileges at JAM Corner.')
            ->action('View Your New Benefits', route('member.benefits'))
            ->line('Thank you for being a valued member of the JAM Members Club.')
            ->salutation('With appreciation, The JAM Corner Team');
    }

    private function logNotification(User $user): void
    {
        NotificationLog::create([
            'user_id' => $user->id,
            'type'    => 'tier_upgraded',
            'subject' => "Congratulations! You've been upgraded to {$this->newTierName}",
            'status'  => 'sent',
            'sent_at' => now(),
        ]);
    }
}
