package com.cf.imes.framework.security.test;

import cn.hutool.core.util.RandomUtil;
import com.cf.imes.framework.security.core.LoginUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.test.context.support.WithSecurityContextFactory;

import java.util.Collections;

/**
 * security mock loginuser
 *
 * @author Gqr
 * @since 2025/9/8 11:17
 */
public class WithMockLoginUserSecurityContextFactory implements WithSecurityContextFactory<WithMockLoginUser> {

    @Override
    public SecurityContext createSecurityContext(WithMockLoginUser annotation) {
        SecurityContext context = SecurityContextHolder.createEmptyContext();

        LoginUser loginUser = new LoginUser();
        long annotationUserId = annotation.userId();
        long annotationOrganId = annotation.organId();
        String username = annotation.username();

        loginUser.setId(annotationUserId == 0L ? RandomUtil.randomLong() : annotationUserId);
        loginUser.setNickname(StringUtils.isNotEmpty(username) ? username : RandomUtil.randomString(10));
        loginUser.setDeptId(RandomUtil.randomLong());
        loginUser.setOrganId(annotationOrganId == 0L ? RandomUtil.randomLong() : annotationOrganId);
        loginUser.setIsSupAdmin(annotation.isSuperAdmin());

        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
                loginUser, null, Collections.emptyList());
        context.setAuthentication(authenticationToken);

        return context;
    }
}
