package com.seer.teach.user.app.auth.service;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.seer.teach.common.enums.ResultCodeEnum;
import com.seer.teach.common.utils.AssertUtils;
import com.seer.teach.user.app.auth.LoginType;
import com.seer.teach.user.app.auth.request.LoginParam;
import com.seer.teach.user.app.auth.response.LoginResp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import jakarta.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


@Slf4j
@Service
public class AppAuthService {

    private final Map<LoginType, LoginStrategy> strategyMap = new ConcurrentHashMap<>(4);

    @Resource
    private List<LoginStrategy> strategyList;


    public AppAuthService(List<LoginStrategy> strategyList) {
        if( CollectionUtil.isNotEmpty(strategyList)){
            for(LoginStrategy strategy : strategyList){
                strategyMap.put(strategy.getType(), strategy);
            }
        }
        log.info("strategyMap:{}", strategyMap);
    }

    /**
     * 登录
     *
     * @param request
     * @return
     */
    @Transactional(rollbackFor = Exception.class,timeout = 120)
    public LoginResp authenticate(LoginParam request) {
        LoginStrategy strategy = strategyMap.get(request.getLoginType());
        AssertUtils.notNull(strategy, ResultCodeEnum.LOGIN_TYPE_ERROR);

        LoginUser user = strategy.authenticate(request);
        StpUtil.login(user.getUserId());

        LoginResp loginResp = new LoginResp();
        loginResp.setToken(StpUtil.getTokenInfo().getTokenValue());
        loginResp.setStatus(user.getStatus());
        loginResp.setApplyStatus(user.getApplyStatus());
        log.info("用户 userId:[{}]登录成功", loginResp);
        return loginResp;
    }
}