<?php

namespace App\Modules\HR\EmployeeSelfService\Middleware;

use App\Models\User;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class EnsureLinkedEmployee
{
    public function handle(Request $request, Closure $next): Response
    {
        $user = $request->user();
        if (! $user instanceof User || $user->isAdmin()) {
            abort(403);
        }
        if ($user->tenant_id === null || $user->employee_id === null) {
            return $this->denied($request, __('me.errors.employee_link_required'));
        }
        $user->loadMissing('employee');
        if ($user->employee === null
            || (int) $user->employee->tenant_id !== (int) $user->tenant_id
            || ! $user->employee->is_active) {
            return $this->denied($request, __('me.errors.employee_inactive'));
        }

        return $next($request);
    }

    private function denied(Request $request, string $message): Response
    {
        if ($request->expectsJson()) {
            abort(403, $message);
        }

        $fallback = $request->user()?->can('dashboard.company')
            ? route('dashboard.index')
            : route('profile.edit');

        return redirect()
            ->to($fallback)
            ->withErrors(['employee' => $message]);
    }
}
