<?php

namespace Api\Login;

use Exception;
use Khofmann\Api\Api;
use Khofmann\ApiError\ApiError;
use Khofmann\Input\Input;
use Khofmann\Response\Response;
use Khofmann\Models\User\User;

class Login extends Api
{
  public function post(): void
  {
    // Fetch all required inputs.
    // Throw 400 error if a required one is missing.
    $missing = [];
    $email = Input::post("email");
    $password = Input::post("password");
    if (empty($email)) array_push($missing, "email");
    if (empty($password)) array_push($missing, "password");
    if (count($missing) > 0) throw ApiError::missingField($missing);

    // Try and log in user.
    // Throw errors according to situation.
    try {
      Response::json(User::logIn($email, $password));
    } catch (Exception $err) {
      switch ($err->getMessage()) {
        case "Failed":
          throw ApiError::failed("Login failed");
        case "NotFound":
          throw ApiError::notFound("user");
        case "Invalid":
          throw ApiError::unauthorized("Invalid username or password");
        default:
          throw $err;
      }
    }
  }
}
