<?php

namespace App\Modules\HR\Recruitment\Listeners;

use App\Models\User;
use App\Modules\Admin\Tenancy\Models\Tenant;
use App\Modules\HR\Recruitment\Events\RecruitmentApplicationCreated;
use App\Modules\HR\Recruitment\Notifications\CareerApplicationReceivedNotification;
use App\Modules\HR\Recruitment\Notifications\CareerApplicationSubmittedStaffNotification;
use Illuminate\Support\Facades\Notification;

class CareerPortalApplicationNotifier
{
    public function handle(RecruitmentApplicationCreated $event): void
    {
        $app = $event->application->loadMissing('candidate');
        if ($app->source !== 'career_portal' || ! $app->tracking_token) {
            return;
        }

        $email = $app->candidate?->email;
        if ($email) {
            Notification::route('mail', $email)
                ->notify(new CareerApplicationReceivedNotification(
                    $app,
                    (string) (Tenant::query()->whereKey($app->tenant_id)->value('slug') ?? ''),
                ));
        }

        $staff = User::query()
            ->where('tenant_id', $app->tenant_id)
            ->where('is_active', true)
            ->where('is_admin', false)
            ->limit(20)
            ->get();

        if ($staff->isNotEmpty()) {
            Notification::send($staff, new CareerApplicationSubmittedStaffNotification($app));
        }
    }
}
