<?php

namespace App\Middlewares;

class RoleMiddleware
{
  private array $roles;

  public function __construct(string ...$roles)
  {
    $this->roles = $roles;
  }

  public function handle(): void
  {
    if (!isset($_SESSION['user'])) {
      redirect('LOGIN');
    }

    $userRole = $_SESSION['user']['role'];

    if (!in_array($userRole, $this->roles, true)) {
      $this->redirectByRole($userRole);
    }
  }

  private function redirectByRole(string $role): never
  {
    match ($role) {
      'ADMIN' => redirect('DASHBOARD'),
      'USER' => redirect('HOME'),
      'TEKNISI' => redirect('TEKNISI'),
      default => redirect('LOGIN'),
    };

    exit;
  }
}
