<?php

namespace App\Jobs;

use App\Enums\BookingParticipantStatusEnum;
use App\Enums\BookingStatusEnum;
use App\Enums\NotificationTypeEnum;
use App\Models\Booking;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;

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

    private const CONFIRMATION_WINDOW_MINUTES = 120;
    private const CONFIRMATION_THRESHOLD = 0.8;

    public function handle(): void
    {
        $cutoff = now()->subMinutes(self::CONFIRMATION_WINDOW_MINUTES);

        $bookings = Booking::where('status', BookingStatusEnum::PENDING->value)
            ->where('created_at', '<=', $cutoff)
            ->with(['participants', 'member'])
            ->get();

        foreach ($bookings as $booking) {
            $total = $booking->participants->count();
            $confirmed = $booking->participants
                ->where('status', BookingParticipantStatusEnum::CONFIRMED->value)
                ->count();

            if ($total > 0 && ($confirmed / $total) < self::CONFIRMATION_THRESHOLD) {
                $booking->update(['status' => BookingStatusEnum::CANCELLED->value]);
                $this->notifyOwner($booking);
            }
        }
    }

    private function notifyOwner(Booking $booking): void
    {
        $owner = $booking->member;
        if (!$owner) {
            return;
        }

        DB::table('notifications')->insert([
            'type' => NotificationTypeEnum::BOOKING_CANCELLED->value,
            'notifiable_type' => \App\Models\Member::class,
            'notifiable_id' => $owner->id,
            'data' => json_encode([
                'title' => __('Booking Cancelled'),
                'message' => __('Your booking was automatically cancelled because less than 80% of participants confirmed within 120 minutes.'),
                'booking_id' => $booking->id,
            ]),
            'created_at' => now(),
            'updated_at' => now(),
        ]);
    }
}
