package com.atlassian.stash.internal.auth.trusted;

import com.atlassian.security.auth.trustedapps.BouncyCastleEncryptionProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Locale;
import java.util.UUID;

/**
 * Generates "safe" UID's using Java's {@code UUID} when the Trusted Apps {@code UIDGenerator} fails.
 * <p>
 * See <a href="https://ecosystem.atlassian.net/browse/TRUST-52">TRUST-52</a> for more details.
 *
 * @since 3.2
 */
public class SafeEncryptionProvider extends BouncyCastleEncryptionProvider {

    private static final Logger log = LoggerFactory.getLogger(SafeEncryptionProvider.class);

    @Override
    public String generateUID() {
        try {
            return super.generateUID();
        } catch (Exception e) {
            log.warn("UID generation failed. Falling back on UUID", e);

            return generateUidFromUuid();
        }
    }

    String generateUidFromUuid() {
        return UUID.randomUUID().toString() //36 characters
                .replace("-", "")           //Shorten to 32 characters, matching UIDGenerator
                .toUpperCase(Locale.US);    //Convert to uppercase, matching UIDGenerator
    }
}
