package org.lingniu.sdk.service;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService;
import org.springframework.stereotype.Component;

import java.util.Collections;

@Component
public class RedisOAuth2AuthorizedClientService implements OAuth2AuthorizedClientService {
    
    private final RedisOAuth2AuthorizedClientRepository repository;
    
    public RedisOAuth2AuthorizedClientService(RedisOAuth2AuthorizedClientRepository repository) {
        this.repository = repository;
    }
    
    @Override
    public <T extends OAuth2AuthorizedClient> T loadAuthorizedClient(
            String clientRegistrationId, String principalName) {
        
        // 从 Redis 加载
        Authentication authentication = createAuthentication(principalName);
        return repository.loadAuthorizedClient(clientRegistrationId, authentication, null);
    }
    
    @Override
    public void saveAuthorizedClient(
            OAuth2AuthorizedClient authorizedClient, Authentication principal) {
        
        repository.saveAuthorizedClient(authorizedClient, principal, null, null);
    }
    
    @Override
    public void removeAuthorizedClient(String clientRegistrationId, String principalName) {
        Authentication authentication = createAuthentication(principalName);
        repository.removeAuthorizedClient(clientRegistrationId, authentication, null, null);
    }

    
    private Authentication createAuthentication(String principalName) {
        return new UsernamePasswordAuthenticationToken(
            principalName, 
            null, 
            Collections.emptyList()
        );
    }
}