package tech.easyflow.usercenter.controller.auth;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import tech.easyflow.auth.entity.CredentialKeyVO;
import tech.easyflow.auth.entity.EncryptedCredentialDTO;
import tech.easyflow.auth.entity.LoginDTO;
import tech.easyflow.auth.entity.LoginVO;
import tech.easyflow.auth.service.AuthCredentialKeyService;
import tech.easyflow.auth.service.AuthService;
import tech.easyflow.common.captcha.tainai.CaptchaVerificationService;
import tech.easyflow.common.domain.Result;
import tech.easyflow.common.web.jsonbody.JsonBody;

import javax.annotation.Resource;
import java.util.List;

/**
 * 认证
 */
@RestController
@RequestMapping("/userCenter/auth/")
public class UcAuthController {

    @Resource
    private AuthService authService;
    @Resource
    private AuthCredentialKeyService credentialKeyService;
    @Resource
    private CaptchaVerificationService captchaVerificationService;

    /**
     * 获取登录加密公钥。
     */
    @GetMapping("credential-key")
    public Result<CredentialKeyVO> credentialKey() {
        return Result.ok(credentialKeyService.getCurrentCredentialKey());
    }

    /**
     * 登录
     * @param encryptedCredential 加密登录参数
     */
    @PostMapping("login")
    public Result<LoginVO> login(@JsonBody EncryptedCredentialDTO encryptedCredential) {
        JSONObject payload = credentialKeyService.decryptPayload(encryptedCredential);
        if (!captchaVerificationService.verify(payload.getString("validToken"))) {
            return captchaVerificationService.failureResult();
        }
        LoginDTO loginDTO = toLoginDTO(payload);
        LoginVO res = authService.login(loginDTO);
        return Result.ok(res);
    }

    /**
     * 登出
     */
    @PostMapping("logout")
    public Result<Void> logout() {
        StpUtil.logout();
        return Result.ok();
    }

    /**
     * 获取权限
     */
    @GetMapping("getPermissions")
    public Result<List<String>> getPermissions() {
        List<String> permissionList = StpUtil.getPermissionList();
        return Result.ok(permissionList);
    }

    private LoginDTO toLoginDTO(JSONObject payload) {
        LoginDTO loginDTO = new LoginDTO();
        loginDTO.setAccount(payload.getString("account"));
        loginDTO.setPassword(payload.getString("password"));
        return loginDTO;
    }
}
