package mx.gob.slp.baseadminweb.configuration.security;

import org.springframework.beans.factory.ObjectProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.stereotype.Service;

@Service
public class ApiAuthService {

    private final ObjectProvider<CognitoAuthService> cognitoAuthService;
    private final ObjectProvider<LocalJwtAuthService> localJwtAuthService;

    public ApiAuthService(ObjectProvider<CognitoAuthService> cognitoAuthService,
                          ObjectProvider<LocalJwtAuthService> localJwtAuthService) {
        this.cognitoAuthService = cognitoAuthService;
        this.localJwtAuthService = localJwtAuthService;
    }

    public ApiLoginResponse login(String username, String password) {
        CognitoAuthService cognito = cognitoAuthService.getIfAvailable();
        if (cognito != null) {
            return cognito.login(username, password);
        }

        LocalJwtAuthService local = localJwtAuthService.getIfAvailable();
        if (local != null) {
            return local.login(username, password);
        }

        throw new IllegalStateException("No hay proveedor de autenticacion API configurado.");
    }

    public ApiLoginResponse refresh(String refreshToken) {
        if (refreshToken == null || refreshToken.isBlank()) {
            throw new BadCredentialsException("El refresh token es obligatorio.");
        }

        CognitoAuthService cognito = cognitoAuthService.getIfAvailable();
        if (cognito != null) {
            return cognito.refresh(refreshToken);
        }

        LocalJwtAuthService local = localJwtAuthService.getIfAvailable();
        if (local != null) {
            return local.refresh(refreshToken);
        }

        throw new IllegalStateException("No hay proveedor de autenticacion API configurado.");
    }
}