<?php

namespace App\Listeners;

use App\Events\BookingCreated;
use App\Models\AppNotification;
use App\Notifications\BookingConfirmation;
use App\Notifications\BookingCreatedPush;
use App\Notifications\BookingOwnerConfirmation;
use Illuminate\Support\Facades\Notification;

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

        // Email al cliente si tiene email
        if ($booking->customer?->email) {
            Notification::route('mail', $booking->customer->email)
                ->notify(new BookingConfirmation($booking));
        }

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

        // Notificación in-app para los admins de la empresa
        $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.created',
                'title'      => 'Nueva reserva',
                'message'    => "{$booking->customer->fullName()} reservó {$booking->service->name} para el "
                                .$booking->scheduled_at?->format('d/m H:i'),
                'icon'       => 'calendar',
                'color'      => 'indigo',
                '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 BookingCreatedPush($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();
    }
}
