<?php

namespace App\Modules\HR\Attendance\Listeners;

use App\Models\User;
use App\Modules\HR\Attendance\Events\AttendanceCorrectionApproved;
use App\Modules\HR\Attendance\Events\AttendanceCorrectionRejected;
use App\Modules\HR\Attendance\Events\AttendanceCorrectionSubmitted;
use App\Modules\HR\Attendance\Models\AttendanceCorrectionRequest;
use App\Modules\HR\Attendance\Notifications\AttendanceCorrectionResolvedNotification;
use App\Modules\HR\Attendance\Notifications\AttendanceCorrectionSubmittedNotification;
use Illuminate\Support\Facades\Notification as NotificationFacade;

class AttendanceCorrectionNotificationListener
{
    public function handleSubmitted(AttendanceCorrectionSubmitted $event): void
    {
        $recipients = $this->reviewers((int) $event->correction->tenant_id);
        if ($recipients->isNotEmpty()) {
            NotificationFacade::send(
                $recipients,
                new AttendanceCorrectionSubmittedNotification($event->correction),
            );
        }
    }

    public function handleApproved(AttendanceCorrectionApproved $event): void
    {
        $this->notifyEmployee($event->correction, 'approved');
    }

    public function handleRejected(AttendanceCorrectionRejected $event): void
    {
        $this->notifyEmployee($event->correction, 'rejected');
    }

    private function notifyEmployee(AttendanceCorrectionRequest $correction, string $resolution): void
    {
        $correction->loadMissing('employee.user');
        $user = $correction->employee?->user;
        if (! $user instanceof User) {
            return;
        }
        $user->notify(new AttendanceCorrectionResolvedNotification($correction, $resolution));
    }

    /**
     * @return \Illuminate\Support\Collection<int, User>
     */
    private function reviewers(int $tenantId)
    {
        return User::query()
            ->where('tenant_id', $tenantId)
            ->where('is_admin', false)
            ->get()
            ->filter(fn (User $u): bool => $u->can('attendance.corrections.review'));
    }
}
