<?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 PointsExpiryReminderNotification extends Notification implements ShouldQueue
{
    use Queueable;

    public function __construct(
        public int    $pointsBalance,
        public string $expiryDate,
    ) {}

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

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

        return (new MailMessage)
            ->subject('Your JAM Members Club points are expiring soon')
            ->greeting("Hi {$notifiable->first_name},")
            ->line("This is a friendly reminder that your **{$this->pointsBalance} points** will expire on **{$this->expiryDate}**.")
            ->line("Points are assessed for tier qualification before they expire — so your current tier status won't be affected retroactively, but expired points won't count toward future tier assessments.")
            ->line("**Keep earning!** Visit JAM Corner to accumulate new points and maintain your tier status.")
            ->action('View Your Dashboard', route('member.dashboard'))
            ->line('If you have any questions about your points, please don\'t hesitate to contact us.')
            ->salutation('Warm regards, The JAM Corner Team');
    }

    private function logNotification(User $user): void
    {
        NotificationLog::create([
            'user_id' => $user->id,
            'type'    => 'expiry_reminder',
            'subject' => 'Your JAM Members Club points are expiring soon',
            'status'  => 'sent',
            'sent_at' => now(),
        ]);
    }
}
