package com.eshore.gringotts.web.domain.controller;

import cn.hutool.core.util.StrUtil;
import com.eshore.gringotts.web.configuration.amis.AmisResponse;
import com.eshore.gringotts.web.domain.entity.User;
import com.eshore.gringotts.web.domain.service.UserService;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 登陆接口
 *
 * @author lanyuanxiaoyao
 * @date 2024-11-14
 */
@RestController
@RequestMapping("/user")
public class UserController {
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping("/state")
    public AmisResponse<UserService.UserInformation> state() {
        return AmisResponse.responseSuccess(userService.state());
    }

    @PostMapping("/register")
    public void register(@RequestBody RegisterRequest request) {
        logger.info("Register request: {}", request);
        userService.register(request.username, request.password, request.role);
    }

    @PostMapping("/login")
    public AmisResponse<UserService.UserInformation> login(@RequestBody LoginRequest request) {
        logger.info("Login request: {}", request);
        return AmisResponse.responseSuccess(userService.login(request.username, request.password));
    }

    @GetMapping("/logout")
    public void logout() {
        userService.logout();
    }

    @GetMapping("/exists_username/{username}")
    public void existsUsername(@PathVariable("username") String username) {
        if (userService.exitsUsername(username)) {
            throw new RuntimeException(StrUtil.format("{} 已存在", username));
        }
    }

    @Data
    public static final class LoginRequest {
        private String username;
        private String password;
        private String checkCode;
    }

    @Data
    public static final class RegisterRequest {
        private String username;
        private String password;
        private User.Role role;
    }
}
