package com.agileboot.auth.service.strategy;

import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.stp.parameter.SaLoginParameter;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.agileboot.auth.pojo.form.PasswordLoginBody;
import com.agileboot.auth.pojo.vo.CurrentLoginUserVO;
import com.agileboot.auth.pojo.vo.LoginVO;
import com.agileboot.auth.properties.CaptchaProperties;
import com.agileboot.auth.service.IAuthStrategy;
import com.agileboot.auth.service.SysLoginService;
import com.agileboot.common.core.enums.LoginType;
import com.agileboot.common.core.exception.BizException;
import com.agileboot.common.core.utils.ValidatorUtils;
import com.agileboot.common.satoken.pojo.LoginUser;
import com.agileboot.common.satoken.utils.LoginHelper;
import com.agileboot.system.client.vo.SysClientVO;
import com.agileboot.system.role.service.ISysRoleService;
import com.agileboot.system.role.vo.RoleVO;
import com.agileboot.system.user.dto.UserInfo;
import com.agileboot.system.user.service.ISysUserService;
import com.alibaba.fastjson2.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * 密码认证策略
 *
 * @author Michelle.Chung
 */
@Slf4j
@Service("password" + IAuthStrategy.BASE_NAME)
@RequiredArgsConstructor
public class PasswordAuthStrategy implements IAuthStrategy {

    private final ISysUserService userService;
    private final SysLoginService loginService;
    private final CaptchaProperties captchaProperties;
    private final ISysRoleService roleService;

    @Override
    public LoginVO login(String body, SysClientVO client) {
        PasswordLoginBody loginBody = JSONObject.parseObject(body, PasswordLoginBody.class);
        ValidatorUtils.validate(loginBody);
        String username = loginBody.getUsername();
        String password = loginBody.getPassword();
        String code = loginBody.getCode();
        String uuid = loginBody.getUuid();

        // 验证码开关
        if (captchaProperties.getEnabled()) {
            loginService.validateCaptcha(null, null, code, uuid);
        }


        Long clientId = client.getId();
        LoginUser loginUser = userService.getUserInfo(username);
        if (!Objects.equals(loginUser.getClientId(), clientId)) {
            throw new BizException("client.not.match");
        }
        loginService.checkLogin(LoginType.PASSWORD, null, loginUser.getUsername(), () -> !BCrypt.checkpw(password, loginUser.getPassword()));

        loginUser.setClientKey(client.getClientKey());
        loginUser.setDeviceType(client.getDeviceType());
        SaLoginParameter model = new SaLoginParameter();
        model.setDeviceType(client.getDeviceType());
        // 自定义分配 不同用户体系 不同 token 授权时间 不设置默认走全局 yml 配置
        // 例如: 后台用户30分钟过期 app用户1天过期
        model.setTimeout(client.getTimeout());
        model.setActiveTimeout(client.getActiveTimeout());
        model.setExtra(LoginHelper.CLIENT_KEY, clientId);
        // 生成token
        LoginHelper.login(loginUser, model);

        LoginVO loginVo = new LoginVO();
        loginVo.setAccessToken(StpUtil.getTokenValue());
        loginVo.setExpireIn(StpUtil.getTokenTimeout());
        loginVo.setClientId(clientId);

        RoleVO roleInfo = roleService.getRoleInfo(loginUser.getRoleId());
        CurrentLoginUserVO vo = new CurrentLoginUserVO();
        vo.setRoleKey(roleInfo.getRoleKey());
        vo.setUserInfo(BeanUtil.copyProperties(roleInfo, UserInfo.class));
        loginVo.setCurrentUser(vo);
        return loginVo;
    }
}
