package com.ssyf.module.auth.gauth;

import cn.hutool.core.util.StrUtil;
import com.ssyf.common.web.apicode.ApiCodeUser;
import com.ssyf.common.web.error.ServiceRuntimeException;
import com.ssyf.common.web.result.Result;
import com.ssyf.module.auth.domain.entity.User;
import com.ssyf.module.auth.domain.query.UserQuery;
import com.ssyf.module.auth.service.UserService;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@RestController
@RequestMapping("/share/api/auth")
@CrossOrigin(origins = "*") // 允许跨域，方便本地测试
public class AuthController {

    @Autowired
    private TwoFactorAuthService tfaService;
    @Autowired
    private UserService userService;

    /**
     * 更新用户的secret key
     */
    @PostMapping("/2fa/update-secret/{uuid}")
    public Result<String> updateSecretKey(@PathVariable String uuid) {
        // 验证用户是否存在
        User user = userService.getOneByUid(uuid);
        if (user == null) {
            throw new ServiceRuntimeException(ApiCodeUser.PARAMETER_ERROR.getCode(), "用户不存在");
        }

        // 校验用户是否已有 secret key
        if (StrUtil.isBlank(user.getSecretKey())) {
            throw new ServiceRuntimeException(ApiCodeUser.PARAMETER_ERROR.getCode(), "用户尚未启用两步验证，无法更新密钥");
        }

        // 生成新的密钥并更新
        String newSecretKey = tfaService.generateSecretKey();
        userService.updateByUid(uuid, new UserQuery().setSecretKey(newSecretKey));

        // 返回新生成的 secret key
        return Result.success(newSecretKey);
    }

    /**
     * 第一步：用户请求开启 2FA，后端生成密钥和二维码链接
     */
    @GetMapping("/2fa/setup")
    public Result<Map<String, String>> setup2fa(@RequestParam String username) {
        User user = userService.getOneByUsername(username);
        if (user == null) {
            ServiceRuntimeException.throw0(ApiCodeUser.PARAMETER_ERROR.getCode(), "用户不存在");
        }

        if(StrUtil.isNotBlank(user.getSecretKey())){
            return Result.success();
        }

        String secretKey = StrUtil.isNotBlank(user.getSecretKey()) ? user.getSecretKey() : tfaService.generateSecretKey();

        // 生成二维码内容字符串
        String qrCodeUrl = tfaService.getQrCodeUrl(secretKey, username, user.getUsername());

        Map<String, String> response = new HashMap<>();
        response.put("secretKey", secretKey);
        response.put("qrCodeUrl", qrCodeUrl);
        return Result.success(response);
    }

    /**
     * 第二步：用户扫描二维码后输入验证码，后端验证并正式开启 2FA
     */
    @PostMapping("/2fa/verify")
    public Result verify2fa(@RequestBody VerifyRequest request) {
        User user = this.userService.loginByUsername(request.getUsername() ,request.getPassword());
        String secretKey =StrUtil.isNotBlank(user.getSecretKey()) ? user.getSecretKey() :  request.getSecretKey();
        // 验证代码
        boolean isCodeValid = tfaService.validateCode(secretKey, request.getCode());

        if (isCodeValid) {
            // 验证通过，将 Secret Key 正式绑定到用户，并开启状态
            if(!Objects.equals(user.getSecretKey(), request.getSecretKey())){
                userService.updateByUid(user.getUid(), new UserQuery().setSecretKey(request.getSecretKey()));
            }
            String token =userService.loginAndGetToken(user);
            return Result.success(token);
        }
        return Result.fail(ApiCodeUser.PARAMETER_ERROR.getCode(), "验证码错误");
    }

    @Data
    public static class VerifyRequest {
        private String username;
        private String password;
        private String secretKey;
        private int code;
    }
}