use authdb::{AuthDB, AuthToken};
use http::{response::Response, status::StatusCode, Error};

pub async fn handle_auth(
    auth_ctx: &AuthDB,
    auth_token: AuthToken,
) -> Result<http::Response<String>, Error> {
    match auth_ctx.authenticate(auth_token).await {
        Ok(Some(session)) => match serde_json::to_string(&session) {
            Ok(session_token) => Response::builder()
                .status(StatusCode::OK)
                .body(session_token),
            Err(_) => Response::builder()
                .status(StatusCode::INTERNAL_SERVER_ERROR)
                .body("".to_owned()),
        },
        Ok(None) => Response::builder()
            .status(StatusCode::UNAUTHORIZED)
            .body("".to_owned()),
        Err(_) => Response::builder()
            .status(StatusCode::INTERNAL_SERVER_ERROR)
            .body("".to_owned()),
    }
}
