import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONObject;
import sailpoint.connector.webservices.WebServicesClient;
import sailpoint.object.ProvisioningPlan;
import sailpoint.object.ProvisioningPlan.AccountRequest;
import sailpoint.object.ProvisioningPlan.AttributeRequest;

// -----------------------------------------------------------------------------
// Helper methods (declared first: BeanShell executes top-to-bottom and does
// not hoist method declarations the way standard Java does)
// -----------------------------------------------------------------------------

String safeTrim(String s) {
    return (s == null) ? "" : s.trim();
}

String stripTrailingSlash(String url) {
    String clean = safeTrim(url);
    while (clean.endsWith("/")) {
        clean = clean.substring(0, clean.length() - 1);
    }
    return clean;
}

String getNativeIdentity(ProvisioningPlan plan) {
    if (plan == null) return null;
    List accountRequests = plan.getAccountRequests();
    if (accountRequests == null || accountRequests.isEmpty()) return null;

    AccountRequest acctReq = (AccountRequest) accountRequests.get(0);
    return acctReq.getNativeIdentity();
}

String getPlanAttribute(ProvisioningPlan plan, String attrName) {
    if (plan == null || attrName == null) return null;
    List accountRequests = plan.getAccountRequests();
    if (accountRequests == null || accountRequests.isEmpty()) return null;

    for (int i = 0; i < accountRequests.size(); i++) {
        AccountRequest acctReq = (AccountRequest) accountRequests.get(i);
        List attrReqs = acctReq.getAttributeRequests();
        if (attrReqs == null) continue;

        for (int j = 0; j < attrReqs.size(); j++) {
            AttributeRequest attrReq = (AttributeRequest) attrReqs.get(j);
            if (attrName.equals(attrReq.getName())) {
                Object value = attrReq.getValue();
                return (value == null) ? null : value.toString();
            }
        }
    }
    return null;
}

// Fetches an OAuth2 Client Credentials token from the secondary auth server
// using the rule-provided restClient instance (never instantiate new WebServicesClient()).
String fetchSecondaryBearerToken(
    WebServicesClient client,
    String tokenUrl,
    String clientId,
    String clientSecret,
    String scope
) {
    if (client == null) {
        throw new RuntimeException("restClient is null in Before Operation rule context.");
    }

    Map clientArgs = new HashMap();
    clientArgs.put(WebServicesClient.ARG_URL, tokenUrl);
    client.configure(clientArgs);

    Map tokenHeaders = new HashMap();
    tokenHeaders.put("Content-Type", "application/x-www-form-urlencoded");
    tokenHeaders.put("Accept", "application/json");

    Map formPayload = new HashMap();
    formPayload.put("grant_type", "client_credentials");
    formPayload.put("client_id", clientId);
    formPayload.put("client_secret", clientSecret);
    if (scope.length() > 0) {
        formPayload.put("scope", scope);
    }

    List allowedStatuses = new ArrayList();
    allowedStatuses.add("2**");

    String rawResponse = client.executePost(tokenUrl, formPayload, tokenHeaders, allowedStatuses);
    if (rawResponse == null || rawResponse.trim().length() == 0) {
        throw new RuntimeException("Secondary OAuth2 token endpoint returned an empty response.");
    }

    JSONObject tokenJson = new JSONObject(rawResponse);
    String accessToken = tokenJson.optString("access_token", "");
    if (accessToken == null || accessToken.trim().length() == 0) {
        throw new RuntimeException("Secondary OAuth2 response did not contain an access_token.");
    }

    return accessToken.trim();
}

// -----------------------------------------------------------------------------
// Main Rule Logic
// -----------------------------------------------------------------------------

String logPrefix = "MULTI_ENDPOINT_OAUTH2_BEFORE_RULE";
String operationType = (requestEndPoint != null) ? safeTrim(requestEndPoint.getOperationType()) : "";
log.info(logPrefix + ": Starting execution for operationType=" + operationType);

if (requestEndPoint == null) {
    throw new RuntimeException(logPrefix + ": requestEndPoint is null.");
}

// 1. Read secondary OAuth2 and API attributes from the source.
//    If using ISC Secrets Management when the primary API uses BasicLogin,
//    bind client_secret_credential_provider_path (or clientKeySpec_credential_provider_path)
//    so SailPoint resolves secondaryClientSecret automatically from your vault.
String secondaryApiBaseUrl = stripTrailingSlash((String) application.getAttributeValue("provisioningApiUrl"));
String secondaryTokenUrl   = safeTrim((String) application.getAttributeValue("secondaryTokenUrl"));
String secondaryClientId   = safeTrim((String) application.getAttributeValue("secondaryClientId"));
String secondaryScope      = safeTrim((String) application.getAttributeValue("secondaryScope"));
String secondarySecret     = (String) application.getAttributeValue("client_secret");

// 2. Fail closed on missing configuration.
if (secondaryApiBaseUrl.length() == 0 || secondaryTokenUrl.length() == 0) {
    log.error(logPrefix + ": Missing provisioningApiUrl or secondaryTokenUrl on source.");
    throw new RuntimeException(logPrefix + ": Secondary API or Token URL is not configured.");
}

if (secondaryClientId.length() == 0 || secondarySecret == null || secondarySecret.trim().length() == 0) {
    log.error(logPrefix + ": Missing secondary OAuth2 client credentials on source.");
    throw new RuntimeException(logPrefix + ": Secondary OAuth2 clientId or client_secret is not configured.");
}

// 3. Obtain a fresh access token from the secondary authorization server.
//    For high-throughput provisioning, consider caching the token with an expiry
//    buffer instead of requesting a new token on every single account operation.
String secondaryToken = fetchSecondaryBearerToken(
    restClient,
    secondaryTokenUrl,
    secondaryClientId,
    secondarySecret,
    secondaryScope
);

String nativeIdentity = safeTrim(getNativeIdentity(provisioningPlan));
String targetUrl;
String httpMethod;
JSONObject payloadJson = new JSONObject();

if ("Create Account".equals(operationType)) {
    targetUrl = secondaryApiBaseUrl + "/v1/users";
    httpMethod = "POST";

    String userName = safeTrim(getPlanAttribute(provisioningPlan, "userName"));
    String email    = safeTrim(getPlanAttribute(provisioningPlan, "email"));
    if (userName.length() == 0) {
        throw new RuntimeException(logPrefix + ": Create Account requires userName in the plan.");
    }
    payloadJson.put("userName", userName);
    if (email.length() > 0) payloadJson.put("email", email);
} else if ("Update Account".equals(operationType)) {
    if (nativeIdentity.length() == 0) {
        throw new RuntimeException(logPrefix + ": Update Account requires nativeIdentity.");
    }
    targetUrl = secondaryApiBaseUrl + "/v1/users/" + URLEncoder.encode(nativeIdentity, "UTF-8");
    httpMethod = "PATCH";

    String email = getPlanAttribute(provisioningPlan, "email");
    if (email != null) payloadJson.put("email", email);
} else {
    throw new RuntimeException(logPrefix + ": Unsupported operationType for this rule: " + operationType);
}

String payload = payloadJson.toString();

// 4. Override destination URL and HTTP method.
requestEndPoint.setFullUrl(targetUrl);
requestEndPoint.setHttpMethodType(httpMethod);

// 5. Replace headers with a brand-new Map so primary API credentials are never sent
//    to the secondary API host.
Map headerMap = new HashMap();
headerMap.put("Authorization", "Bearer " + secondaryToken);
headerMap.put("Content-Type", "application/json");
headerMap.put("Accept", "application/json");
requestEndPoint.setHeader(headerMap);

// 6. Set the raw JSON body.
Map bodyMap = new HashMap();
bodyMap.put("bodyFormat", "raw");
bodyMap.put("bodyFormData", null);
bodyMap.put("jsonBody", payload);
requestEndPoint.setBody(bodyMap);

// Never log secondarySecret, secondaryToken, raw token response, or headerMap.
log.info(logPrefix + ": Routed " + operationType + " to " + targetUrl + " (payloadLength=" + payload.length() + ")");

return requestEndPoint;
