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

    public function __construct(
        public int    $points,
        public string $reason,
        public int    $newBalance,
    ) {}

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

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

        return (new MailMessage)
            ->subject("Points adjustment — {$this->points} points deducted")
            ->greeting("Hi {$notifiable->first_name},")
            ->line("A points adjustment has been made on your account.")
            ->line("**Details:**")
            ->line("• Points deducted: {$this->points}")
            ->line("• Reason: {$this->reason}")
            ->line("Your new points balance is **{$this->newBalance} points**.")
            ->action('View Points History', route('member.points'))
            ->line('If you have any questions, please contact us.')
            ->salutation('Best regards, The JAM Corner Team');
    }

    private function logNotification(User $user): void
    {
        NotificationLog::create([
            'user_id' => $user->id,
            'type'    => 'points_debited',
            'subject' => "Points adjustment — {$this->points} points deducted",
            'status'  => 'sent',
            'sent_at' => now(),
        ]);
    }
}
