package com.micer.easyball.service.Impl;

import com.micer.easyball.enums.ResultCode;
import com.micer.easyball.pojo.LoginUser;
import com.micer.easyball.pojo.ResponseResult;
import com.micer.easyball.pojo.User;
import com.micer.easyball.service.LoginService;
import com.micer.easyball.utils.JwtUtil;
import com.micer.easyball.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import io.jsonwebtoken.Claims;

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

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 登出
     * @return
     */
    @Override
    public ResponseResult logout() {
        // 获取当前 Token（来自请求头）
        ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String token = null;
        if (attrs != null) {
            HttpServletRequest request = attrs.getRequest();
            token = request.getHeader("token");
        }

        // 获取SecurityContextHolder中的用户id
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        String userId = loginUser.getUser().getId();

        // 将 token 加入黑名单（过期时间与 token 剩余有效期一致）
        if (token != null && token.length() > 0) {
            try {
                Claims claims = JwtUtil.parseJWT(token);
                long expirationTime = claims.getExpiration().getTime();
                long currentTime = System.currentTimeMillis();
                long remainingTime = (expirationTime - currentTime) / 1000; // seconds
                if (remainingTime > 0) {
                    redisUtil.set("token_blacklist:" + token, "1", remainingTime);
                }
            } catch (Exception e) {
                // 解析失败，使用默认 24 小时
                redisUtil.set("token_blacklist:" + token, "1", 24 * 60 * 60);
            }
        }

        // 删除用户会话
        redisUtil.del("Easyball Login User:" + userId);
        return new ResponseResult(200, "注销成功");
    }

    /**
     * 登录
     * @return
     */
    @Override
    public ResponseResult login(User user) {
        // 用户认证
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getTelephone(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);

        // 认证没通过，给出提示
        if (Objects.isNull(authenticate)) {
            System.out.println("Login fail");
            return new ResponseResult(303, "登录失败");
        }

        // 认证通过，使用userid生成jwt，jwt存入ResponseResult返回
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        // 检查是否强制修改初始密码
        if (loginUser.getUser().getForceChangePassword() != null && loginUser.getUser().getForceChangePassword()) {
            return new ResponseResult(402, "请修改初始密码", java.util.Collections.singletonMap("requireChange", true));
        }
        String userId = loginUser.getUser().getId();
        String jwt = JwtUtil.createJWT(userId, null);
        Map<String, String> map = new HashMap<>();
        map.put("token", jwt);

        // 把完整的用户信息存入redis，userid作为key
        redisUtil.set("Easyball Login User:" + userId, loginUser);
        redisUtil.expire("Easyball Login User:" + userId, 24 * 60 * 60L);

        return new ResponseResult(200, "登录成功", map);
    }
}
