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

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;

@Service
@ConditionalOnProperty(prefix = "app.cognito", name = "enabled", havingValue = "true")
public class CognitoAuthService {

    private static final String SCANNER_ROLE = "ROLE_SCANNER";

    private final CognitoUserAuthenticator cognitoUserAuthenticator;
    private final CognitoProperties cognitoProperties;

    public CognitoAuthService(CognitoUserAuthenticator cognitoUserAuthenticator,
                              CognitoProperties cognitoProperties) {
        this.cognitoUserAuthenticator = cognitoUserAuthenticator;
        this.cognitoProperties = cognitoProperties;
    }

    public ApiLoginResponse login(String username, String password) {
        CognitoUserAuthenticator.AuthenticationResult result = cognitoUserAuthenticator.authenticate(
                username,
                password,
                cognitoProperties.getScannerClientId(),
                SCANNER_ROLE
        );
        return toLoginResponse(result);
    }

    public ApiLoginResponse refresh(String refreshToken) {
        CognitoUserAuthenticator.AuthenticationResult result = cognitoUserAuthenticator.refresh(
                refreshToken,
                cognitoProperties.getScannerClientId(),
                SCANNER_ROLE
        );
        return toLoginResponse(result);
    }

    private ApiLoginResponse toLoginResponse(CognitoUserAuthenticator.AuthenticationResult result) {
        var tokens = result.tokens();
        return new ApiLoginResponse(
                tokens.accessToken(),
                result.refreshToken(),
                tokens.idToken(),
                tokens.tokenType() != null ? tokens.tokenType() : "Bearer",
                tokens.expiresIn() != null ? tokens.expiresIn() : 0L,
                result.username(),
                result.roles()
        );
    }
}