package com.yaoai.admin.auth;

import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yaoai.common.exception.BizException;
import com.yaoai.common.exception.ErrorCode;
import com.yaoai.domain.entity.AdminUser;
import com.yaoai.domain.mapper.AdminUserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;

@Service
@RequiredArgsConstructor
public class AdminAuthService {

    private final AdminUserMapper adminUserMapper;

    public String login(String username, String password, String ip) {
        AdminUser user = adminUserMapper.selectOne(Wrappers.<AdminUser>lambdaQuery()
                .eq(AdminUser::getUsername, username));

        if (user == null) {
            throw new BizException(ErrorCode.UNAUTHORIZED.getCode(), "用户名或密码错误");
        }

        if (Integer.valueOf(0).equals(user.getStatus())) {
            throw new BizException(ErrorCode.FORBIDDEN.getCode(), "账号已被禁用");
        }

        if (!BCrypt.checkpw(password, user.getPasswordHash())) {
            throw new BizException(ErrorCode.UNAUTHORIZED.getCode(), "用户名或密码错误");
        }

        StpAdminUtil.login(user.getId());

        user.setLastLoginAt(LocalDateTime.now());
        user.setLastLoginIp(ip);
        adminUserMapper.updateById(user);

        return StpAdminUtil.getTokenValue();
    }

    public void logout() {
        StpAdminUtil.logout();
    }

    public AdminUser getCurrentAdmin() {
        Long id = StpAdminUtil.getLoginIdAsLong();
        return adminUserMapper.selectById(id);
    }

    public void changePassword(String oldPassword, String newPassword) {
        if (!StringUtils.hasText(oldPassword) || !StringUtils.hasText(newPassword)) {
            throw new BizException(ErrorCode.INVALID_PARAM.getCode(), "旧密码和新密码不能为空");
        }
        if (newPassword.length() < 8) {
            throw new BizException(ErrorCode.INVALID_PARAM.getCode(), "新密码长度不能少于 8 位");
        }

        Long id = StpAdminUtil.getLoginIdAsLong();
        AdminUser user = adminUserMapper.selectById(id);
        if (user == null) {
            throw new BizException(ErrorCode.UNAUTHORIZED.getCode(), "登录已失效");
        }
        if (!BCrypt.checkpw(oldPassword, user.getPasswordHash())) {
            throw new BizException(ErrorCode.UNAUTHORIZED.getCode(), "旧密码错误");
        }

        user.setPasswordHash(BCrypt.hashpw(newPassword, BCrypt.gensalt()));
        user.setMustChangePassword(0);
        user.setUpdatedAt(LocalDateTime.now());
        adminUserMapper.updateById(user);
    }
}
