<?php

namespace Khofmann\Auth;

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

/**
 * Middleware for optional authenticated routes
 */
class OptAuth implements IMiddleware
{
  /**
   * Request handler
   *
   * Returns 401 if no user is found with the `token`.
   *
   * Keeps session fresh if request is authenticated.
   *
   * @param Request $request Incoming request
   */
  public function handle(Request $request): void
  {
    $token = $request->getHeader("token");

    // No token, since authentication is optional, pass
    if ($token === null) {
      return;
    }

    try {
      // Get user
      $user = User::getByToken($token);

      // Keep fresh
      $user->keepFresh();
    } 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"]);
    }
  }
}
