package cn.reghao.tnb.auth.app.security;

import cn.reghao.tnb.auth.app.security.form.AccountAuthToken;
import cn.reghao.tnb.auth.model.JwtPayload;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author reghao
 * @date 2025-10-24 20:37:59
 */
public class AuthConverter {
    public static JwtPayload getJwtPayload(AccountAuthToken accountAuthToken) {
        int plat = accountAuthToken.getPlat();
        String loginId = accountAuthToken.getLoginId();
        long userId = accountAuthToken.getUserId();
        int loginType = accountAuthToken.getLoginType();
        String authorities = accountAuthToken.getAuthorities().stream()
                .map(GrantedAuthority::getAuthority)
                .collect(Collectors.toList())
                .toString();
        String jti = "";
        return new JwtPayload(plat, loginId, userId, loginType, authorities, jti);
    }

    public static AccountAuthToken getAccountAuthToken(JwtPayload jwtPayload) {
        Integer plat = jwtPayload.getPlat();
        String loginId = jwtPayload.getLoginId();
        long userId = jwtPayload.getUserId();
        int loginType = jwtPayload.getLoginType();
        String authoritiesStr = jwtPayload.getAuthorities();
        String authoritiesStr0 = authoritiesStr.replace("[", "").replace("]", "");
        List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList(authoritiesStr0);
        return new AccountAuthToken(plat, loginId, loginType, userId, authorities);
    }
}
