<?php

namespace App\Notifications;

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

class TierDowngradedNotification 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_downgraded', true)) {
            return [];
        }
        return ['mail'];
    }

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

        return (new MailMessage)
            ->subject("Tier update — your membership is now {$this->newTierName}")
            ->greeting("Hi {$notifiable->first_name},")
            ->line("We'd like to let you know that your membership tier has been updated from **{$this->previousTierName}** to **{$this->newTierName}**.")
            ->line("This change is based on your recent visit and spend activity during the quarterly assessment period.")
            ->line("**How to re-qualify:**")
            ->line("• Visit JAM Corner regularly with qualifying spends")
            ->line("• Accumulate enough points within the next quarter")
            ->line("• Your tier will be reassessed at the next quarterly review")
            ->action('Check Your Current Status', route('member.dashboard'))
            ->line('We value your membership and hope to see you back at a higher tier soon!')
            ->salutation('Best regards, The JAM Corner Team');
    }

    private function logNotification(User $user): void
    {
        NotificationLog::create([
            'user_id' => $user->id,
            'type'    => 'tier_downgraded',
            'subject' => "Tier update — your membership is now {$this->newTierName}",
            'status'  => 'sent',
            'sent_at' => now(),
        ]);
    }
}
