package com.ssyf.task.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.ssyf.module.robot.domain.entity.RRobotAccount;
import com.ssyf.third.bmiss.model.ApiResponse;
import com.ssyf.third.bmiss.model.LoginResponse;
import com.ssyf.third.bmiss.services.BusinessService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 机器人会话管理器
 * 负责 Token 的复用与缓存管理
 */
@Slf4j
@Component
public class RobotSessionManager {
    @Lazy
    @Autowired private BusinessService businessService;
    @Lazy
    @Autowired private StringRedisTemplate redisTemplate;

    private static final String KEY_SESSION = "robot:session:";
    // 缓存1小时，确保在配置有效期内，机器人无需重复登录
    private static final long SESSION_EXPIRE_HOURS = 1;

    /**
     * 获取会话：优先查缓存，无则登录
     */
    public LoginResponse getOrRefreshSession(RRobotAccount account) {
        String cacheKey = KEY_SESSION + account.getUuid();

        // 1. 尝试复用
        String json = redisTemplate.opsForValue().get(cacheKey);
        if (StrUtil.isNotBlank(json)) {
            try {
                LoginResponse session = JSONUtil.toBean(json, LoginResponse.class);
                if (StrUtil.isNotBlank(session.getToken())) {
                    return session;
                }
            } catch (Exception e) {
                redisTemplate.delete(cacheKey);
            }
        }

        // 2. 执行登录
        log.debug("无有效会话，执行远程登录: {}", account.getEmail());
        try {
            ApiResponse<LoginResponse> resp = businessService.loginByEmail(account.getEmail(), account.getPassword());
            if (resp != null && resp.isSuccess() && resp.getData() != null) {
                LoginResponse loginData = resp.getData();
                redisTemplate.opsForValue().set(cacheKey, JSONUtil.toJsonStr(loginData), SESSION_EXPIRE_HOURS, TimeUnit.HOURS);
                return loginData;
            } else {
                log.warn("登录失败: {}", account.getEmail());
            }
        } catch (Exception e) {
            log.error("登录接口异常: {}", account.getEmail(), e);
        }
        return null;
    }

    /**
     * 强制失效会话（登出或Token错误时调用）
     */
    public void invalidateSession(String robotUuid) {
        redisTemplate.delete(KEY_SESSION + robotUuid);
    }
}