package com.ytpm.handle;


import com.ytpm.app.enums.LoginType;
import com.ytpm.app.model.YtDyzUser;
import com.ytpm.app.param.LoginParam;
import com.ytpm.general.RepMessage;
import com.ytpm.general.Result;
import com.ytpm.general.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author lih
 * @date 2025/9/4
 */
@Component
public class LoginServiceFactory {

    private final Map<String, AbstractLoginService> loginServiceMap = new ConcurrentHashMap<>();


    /**
     * 通过构造函数注入所有登录服务
     */
    @Autowired
    public LoginServiceFactory(List<AbstractLoginService> loginServices) {
        for (AbstractLoginService service : loginServices) {
            loginServiceMap.put(service.getLoginType().getTypeName(), service);
        }
    }

    /**
     * 根据登录类型获取登录服务
     */
    public AbstractLoginService getLoginService(LoginType loginType) {
        AbstractLoginService service = loginServiceMap.get(loginType.getTypeName());
        if (service == null) {
            throw new RuntimeException("不支持的登录类型: " + loginType);
        }
        return service;
    }

    public Result<YtDyzUser> login(LoginType loginType, LoginParam param, HttpServletRequest request) {
        try {
            AbstractLoginService loginService = getLoginService(loginType);
            YtDyzUser ytDyzUser = loginService.loginHandle(param, request);
            return Result.resultOk(RepMessage.LOGIN_SUCCESS, ytDyzUser);
        } catch (CommonException e) {
            return new Result<>(StatusCode.ACCESS_ERR, e.getMessage());
        } catch (IllegalArgumentException e) {
            return new Result<>(StatusCode.PARAMETER_CHECK_ERR, e.getMessage());
        }
    }

}
