package com.qmth.exam.reserve.controller.student;

import com.qmth.boot.api.annotation.Aac;
import com.qmth.boot.api.constant.ApiConstant;
import com.qmth.boot.api.exception.DefaultExceptionEnum;
import com.qmth.boot.core.rateLimit.entity.RateLimitRule;
import com.qmth.boot.core.rateLimit.service.RateLimitService;
import com.qmth.exam.reserve.bean.Constants;
import com.qmth.exam.reserve.bean.login.LoginReq;
import com.qmth.exam.reserve.bean.login.LoginUser;
import com.qmth.exam.reserve.bean.login.WechatLoginReq;
import com.qmth.exam.reserve.controller.BaseController;
import com.qmth.exam.reserve.service.AuthService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
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;

@RestController
@Api(tags = "【考生端】考生登录相关接口")
@RequestMapping(ApiConstant.DEFAULT_URI_PREFIX + "/student")
@Aac(strict = false, auth = false)
public class StudentLoginController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(StudentLoginController.class);

    @Autowired
    private AuthService authService;

    @Autowired
    private RateLimitService rateLimitService;

    @ApiOperation(value = "考生登录（账号）")
    @PostMapping(value = "/login")
    public LoginUser login(@RequestBody LoginReq req) {
        RateLimitRule limitRule = RateLimitRule.parse(Constants.API_LIMIT_EXPRESSION);
        if (!rateLimitService.getRateLimiter("student_login", null, limitRule).acquire()) {
            throw DefaultExceptionEnum.RATE_LIMITED.exception(Constants.REQUEST_API_BUSY);
        }

        return authService.studentLogin(req);
    }

    @ApiOperation(value = "考生登录（微信号）")
    @PostMapping(value = "/login/for/wechat")
    public LoginUser loginForWechat(@RequestBody WechatLoginReq req) {
        RateLimitRule limitRule = RateLimitRule.parse(Constants.API_LIMIT_EXPRESSION);
        if (!rateLimitService.getRateLimiter("wechat_login", null, limitRule).acquire()) {
            throw DefaultExceptionEnum.RATE_LIMITED.exception(Constants.REQUEST_API_BUSY);
        }

        return authService.wechatLogin(req);
    }

    @Aac(strict = false, auth = true)
    @ApiOperation(value = "考生登出")
    @PostMapping(value = "/logout")
    public void logout() {
        authService.logout(curLoginStudent());
    }

}
