<?php

namespace Khofmann\Auth;

use Exception;
use Pecee\Http\Middleware\IMiddleware;
use Pecee\Http\Request;
use Khofmann\Models\User\User;
use Khofmann\Response\Response;

class AdminAuth implements IMiddleware
{
  public function handle(Request $request): void
  {
    $token = $request->getHeader("token");

    // No token
    if ($token === null) {
      Response::response()
        ->header("Cache-control: no-cache")
        ->header("Access-Control-Allow-Origin: *")
        ->header("Access-Control-Allow-Methods: *")
        ->header("Access-Control-Allow-Headers: *")
        ->httpCode(401)
        ->json(["code" => "Unauthorized", "message" => "Not Authorized"]);
    }

    try {
      $user = User::getByToken($token);
      if (!$user->getIsAdmin()) {
        Response::response()
          ->header("Cache-control: no-cache")
          ->header("Access-Control-Allow-Origin: *")
          ->header("Access-Control-Allow-Methods: *")
          ->header("Access-Control-Allow-Headers: *")
          ->httpCode(401)
          ->json(["code" => "Unauthorized", "message" => "Not Authorized"]);
      }
    } catch (Exception $err) {
      // No user with this token exists
      Response::response()
        ->header("Cache-control: no-cache")
        ->header("Access-Control-Allow-Origin: *")
        ->header("Access-Control-Allow-Methods: *")
        ->header("Access-Control-Allow-Headers: *")
        ->httpCode(401)
        ->json(["code" => "Unauthorized", "message" => "Not Authorized"]);
    }
  }
}
