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

    public function __construct(
        public int    $points,
        public float  $spendAmount,
        public string $visitDate,
        public int    $newBalance,
    ) {}

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

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

        return (new MailMessage)
            ->subject("You've earned {$this->points} points!")
            ->greeting("Hi {$notifiable->first_name},")
            ->line("Great news! **{$this->points} points** have been added to your account.")
            ->line("**Visit details:**")
            ->line("• Date: {$this->visitDate}")
            ->line("• Spend: \${$this->spendAmount}")
            ->line("• Points earned: {$this->points}")
            ->line("Your new points balance is **{$this->newBalance} points**.")
            ->action('View Points History', route('member.points'))
            ->line('Keep visiting to climb the tiers and unlock more benefits!')
            ->salutation('Cheers, The JAM Corner Team');
    }

    private function logNotification(User $user): void
    {
        NotificationLog::create([
            'user_id' => $user->id,
            'type'    => 'points_credited',
            'subject' => "You've earned {$this->points} points!",
            'status'  => 'sent',
            'sent_at' => now(),
        ]);
    }
}
