<?php

namespace App\Listeners;

use App\Events\BookingCancelled;
use App\Models\AppNotification;
use App\Notifications\BookingCancelledNotification;
use App\Notifications\BookingCancelledPush;
use App\Notifications\BookingOwnerCancelledNotification;
use Illuminate\Support\Facades\Notification;

class SendBookingCancelledMail
{
    public function handle(BookingCancelled $event): void
    {
        $booking = $event->booking->loadMissing(['customer', 'service', 'employee.user', 'company']);

        if ($booking->customer?->email) {
            Notification::route('mail', $booking->customer->email)
                ->notify(new BookingCancelledNotification($booking));
        }

        foreach ($this->ownerEmails($booking) as $email) {
            Notification::route('mail', $email)
                ->notify(new BookingOwnerCancelledNotification($booking));
        }

        $adminUsers = $booking->company->users()
            ->whereHas('roles', fn ($q) => $q->where('name', 'company_admin'))
            ->get();

        foreach ($adminUsers as $user) {
            AppNotification::create([
                'company_id' => $booking->company_id,
                'user_id'    => $user->id,
                'type'       => 'booking.cancelled',
                'title'      => 'Reserva cancelada',
                'message'    => "{$booking->customer?->fullName()} canceló {$booking->service?->name} del "
                                .$booking->scheduled_at?->format('d/m H:i'),
                'icon'       => 'calendar',
                'color'      => 'rose',
                'action_url' => route('tenant.bookings.show', $booking, false),
                'data'       => ['booking_id' => $booking->id, 'code' => $booking->code],
                'created_at' => now(),
            ]);
        }

        foreach ($this->pushRecipients($booking, $adminUsers) as $user) {
            $user->notify(new BookingCancelledPush($booking));
        }
    }

    protected function ownerEmails($booking): array
    {
        return $booking->company->users()
            ->whereHas('roles', fn ($q) => $q->where('name', 'company_admin'))
            ->whereNotNull('email')
            ->pluck('email')
            ->push($booking->company->email)
            ->filter()
            ->unique()
            ->values()
            ->all();
    }

    protected function pushRecipients($booking, $adminUsers)
    {
        return $adminUsers
            ->push($booking->employee?->user)
            ->filter()
            ->unique('id')
            ->values();
    }
}
