/// API endpoints for authentication-related functions, like registration and login.
module auth.api;

import handy_http_primitives;
import handy_http_data.json;
import handy_http_handlers.path_handler;
import slf4d;

import auth.model;
import auth.data;
import auth.service;
import auth.data_impl_fs;

@PathMapping(HttpMethod.GET, "/api/me")
void getMyUser(ref ServerHttpRequest request, ref ServerHttpResponse response) {
    AuthContext auth = getAuthContext(request);
    response.writeBodyString(auth.user.username);
}

@PathMapping(HttpMethod.DELETE, "/api/me")
void deleteMyUser(ref ServerHttpRequest request, ref ServerHttpResponse response) {
    AuthContext auth = getAuthContext(request);
    UserRepository userRepo = new FileSystemUserRepository();
    deleteUser(auth.user, userRepo);
    infoF!"Deleted user: %s"(auth.user.username);
}

@PathMapping(HttpMethod.GET, "/api/me/token")
void getNewToken(ref ServerHttpRequest request, ref ServerHttpResponse response) {
    AuthContext auth = getAuthContext(request);
    string token = generateTokenForUser(auth.user);
    response.writeBodyString(token);
    infoF!"Generated token for user: %s"(auth.user.username);
}

struct PasswordChangeRequest {
    string currentPassword;
    string newPassword;
}

@PathMapping(HttpMethod.POST, "/api/me/password")
void changeMyPassword(ref ServerHttpRequest request, ref ServerHttpResponse response) {
    AuthContext auth = getAuthContext(request);
    PasswordChangeRequest data = readJsonBodyAs!PasswordChangeRequest(request);
    changePassword(auth.user, new FileSystemUserRepository(), data.currentPassword, data.newPassword);
    infoF!"User \"%s\" changed their password."(auth.user.username);
}
