<?php

namespace App\Http\Middleware;

use Closure;
use App\Enums\UserType;
use App\Models\Department;
use Illuminate\Http\Request;

class CheckActiveDepartment
{
  public function handle(Request $request, Closure $next)
  {
    if (!in_array(auth()->user()->role, [UserType::User, UserType::Manager, UserType::Director])) {
      return $next($request);
    }

    if (in_array(auth()->user()->role, [UserType::Director]) && str_contains(url()->current(), '/admin/users')) {
      return $next($request);
    }

    $department = Department::active($request)->first();

    if (!$department) {
      return redirect('/admin/dashboard')->with('error', 'Silahkan pilih departemen yang aktif');
    }

    return $next($request);
  }
}
