<?php

namespace App\Jobs;

use App\Enums\BookingStatusEnum;
use App\Enums\NotificationTypeEnum;
use App\Models\Booking;
use App\Models\Member;
use App\Services\NotificationService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class SendBookingRemindersJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Send reminder 30 minutes before booking start.
     * Prevents duplicate by using NotificationService duplicate check.
     */
    public function handle(NotificationService $notificationService): void
    {
        $now = now();
        $reminderWindow = $now->copy()->addMinutes(30);

        // Find bookings that start in the next 30 minutes (today)
        $bookings = Booking::whereDate('booking_date', $now->toDateString())
            ->whereIn('status', [
                BookingStatusEnum::PENDING->value,
                BookingStatusEnum::CONFIRMED->value,
            ])
            ->where('start_time', '>', $now->format('H:i:s'))
            ->where('start_time', '<=', $reminderWindow->format('H:i:s'))
            ->with(['member', 'game', 'participants.member'])
            ->get();

        foreach ($bookings as $booking) {
            $gameName = $booking->game?->name ?? __('Game');
            $title    = __('Booking Reminder');
            $message  = __('Your booking for :game starts in 30 minutes at :time.', [
                'game' => $gameName,
                'time' => $booking->start_time,
            ]);

            // Notify booking owner
            if ($booking->member) {
                $notificationService->sendToMember(
                    $booking->member,
                    NotificationTypeEnum::BOOKING_REMINDER->value,
                    $title,
                    $message,
                    $booking->id
                );
            }

            // Notify all confirmed participants
            $participantMembers = $booking->participants
                ->where('is_creator', false)
                ->pluck('member')
                ->filter();

            foreach ($participantMembers as $member) {
                $notificationService->sendToMember(
                    $member,
                    NotificationTypeEnum::BOOKING_REMINDER->value,
                    $title,
                    $message,
                    $booking->id
                );
            }
        }
    }
}
