package com.yinlihupo.enlish.service.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.yinlihupo.enlish.service.model.vo.login.LoginReqVO;
import com.yinlihupo.enlish.service.model.vo.login.VerificationCodeReqVO;
import com.yinlihupo.enlish.service.service.LoginService;
import com.yinlihupo.framework.biz.operationlog.aspect.ApiOperationLog;
import com.yinlihupo.framework.common.response.Response;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
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;

@RequestMapping("/login/")
@RestController
@Slf4j
public class LoginController {

    @Resource
    private LoginService loginService;

    @PostMapping("login")
    @ApiOperationLog(description = "登录")
    public Response<String> login(@RequestBody LoginReqVO loginReqVO) {
        try {
            loginService.login(loginReqVO.getPhone(), loginReqVO.getName(), loginReqVO.getPassword(), loginReqVO.getCode(), loginReqVO.getInvitationCode());
            return Response.success(StpUtil.getTokenInfo().getTokenValue());
        } catch (Exception e) {
            log.error("注册或登录失败 {}", e.getMessage());
            return Response.fail("注册或登录失败 " + e.getMessage());
        }
    }

    @PostMapping("logout")
    @ApiOperationLog(description = "登出")
    public Response<Void> logout() {
        try {
            StpUtil.logout();
            return Response.success();
        } catch (Exception e) {
            log.error("登出失败 {}", e.getMessage());
            return Response.fail("登出失败 " + e.getMessage());
        }
    }

    @PostMapping("sendVerificationCode")
    @ApiOperationLog(description = "发送验证码")
    public Response<Void> sendVerificationCode(@RequestBody VerificationCodeReqVO verificationCodeReqVO) {
        try {
            loginService.sendVerificationCode(verificationCodeReqVO.getPhone());
            return Response.success();
        } catch (Exception e) {
            log.error("发送验证码失败 {}", e.getMessage());
            return Response.fail("发送验证码失败 " + e.getMessage());
        }
    }

}
