import java.net.URLEncoder;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONObject;
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();
}

// Returns the string value of an attribute request on the first account request,
// or null if the attribute request is not present. Distinguishing null from ""
// lets Update Account send only changed fields without overwriting others.
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;
}

// Builds a properly escaped JSON body via org.json.JSONObject rather than
// string concatenation. If your secondary API uses SOAP/XML instead of REST,
// escape every dynamic value with an xmlEscape() helper before building XML.
String buildPayload(String operationType, ProvisioningPlan plan, String nativeIdentity) {
    JSONObject json = new JSONObject();

    if ("Create Account".equals(operationType)) {
        String userName  = safeTrim(getPlanAttribute(plan, "userName"));
        String firstName = safeTrim(getPlanAttribute(plan, "firstName"));
        String lastName  = safeTrim(getPlanAttribute(plan, "lastName"));
        String email     = safeTrim(getPlanAttribute(plan, "email"));

        if (userName.length() == 0 || firstName.length() == 0 || lastName.length() == 0) {
            throw new RuntimeException("Create Account failed: missing required plan attributes (userName, firstName, or lastName).");
        }

        json.put("userName", userName);
        json.put("firstName", firstName);
        json.put("lastName", lastName);
        if (email.length() > 0) {
            json.put("email", email);
        }
    } else if ("Update Account".equals(operationType)) {
        if (nativeIdentity.length() == 0) {
            throw new RuntimeException("Update Account failed: missing nativeIdentity on provisioning plan.");
        }

        String firstName = getPlanAttribute(plan, "firstName");
        String lastName  = getPlanAttribute(plan, "lastName");
        String email     = getPlanAttribute(plan, "email");

        if (firstName != null) json.put("firstName", firstName);
        if (lastName != null)  json.put("lastName", lastName);
        if (email != null)     json.put("email", email);
    }

    return json.toString();
}

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

String logPrefix = "MULTI_ENDPOINT_BASIC_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 API configuration from source connectorAttributes.
//    If you use a custom encrypted attribute instead of ISC Secrets Management,
//    change "clientKeySpec" below to your custom key (e.g. "provisioningApiPassword").
String secondaryBaseUrl  = stripTrailingSlash((String) application.getAttributeValue("provisioningApiUrl"));
String secondaryUsername = safeTrim((String) application.getAttributeValue("provisioningApiUsername"));
String secondaryPassword = (String) application.getAttributeValue("clientKeySpec");

// 2. Fail closed if configuration is incomplete. Returning requestEndPoint
//    unmodified here would send provisioning calls to the primary Base URL
//    with the primary API credentials.
if (secondaryBaseUrl.length() == 0) {
    log.error(logPrefix + ": Missing provisioningApiUrl connector attribute.");
    throw new RuntimeException(logPrefix + ": provisioningApiUrl is not configured on the source.");
}

if (secondaryUsername.length() == 0 || secondaryPassword == null || secondaryPassword.trim().length() == 0) {
    log.error(logPrefix + ": Missing secondary API credentials on source configuration.");
    throw new RuntimeException(logPrefix + ": Secondary API username or password is not configured on the source.");
}

String nativeIdentity = safeTrim(getNativeIdentity(provisioningPlan));

// 3. Resolve target URL and HTTP method for the current provisioning operation.
String targetUrl;
String httpMethod;
if ("Create Account".equals(operationType)) {
    targetUrl = secondaryBaseUrl + "/v1/accounts";
    httpMethod = "POST";
} else if ("Update Account".equals(operationType)) {
    if (nativeIdentity.length() == 0) {
        throw new RuntimeException(logPrefix + ": Update Account requires nativeIdentity.");
    }
    targetUrl = secondaryBaseUrl + "/v1/accounts/" + URLEncoder.encode(nativeIdentity, "UTF-8");
    httpMethod = "PATCH";
} else {
    throw new RuntimeException(logPrefix + ": Unsupported operationType for this rule: " + operationType);
}

String payload = buildPayload(operationType, provisioningPlan, nativeIdentity);
String basicAuthValue = "Basic " + Base64.getEncoder().encodeToString(
    (secondaryUsername + ":" + secondaryPassword).getBytes("UTF-8")
);

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

// 5. Construct a brand-new Header Map so the primary API's Authorization header
//    is completely stripped and never leaked to the secondary host.
Map headerMap = new HashMap();
headerMap.put("Authorization", basicAuthValue);
headerMap.put("Content-Type", "application/json");
headerMap.put("Accept", "application/json");
requestEndPoint.setHeader(headerMap);

// 6. Set the raw request body. Note that SailPoint uses the "jsonBody" key
//    for raw payloads even when sending non-JSON bodies such as XML/SOAP.
Map bodyMap = new HashMap();
bodyMap.put("bodyFormat", "raw");
bodyMap.put("bodyFormData", null);
bodyMap.put("jsonBody", payload);
requestEndPoint.setBody(bodyMap);

// Log only non-sensitive metadata (never log credentials, auth headers, or full headerMap).
log.info(logPrefix + ": Routed " + operationType + " to " + targetUrl + " (payloadLength=" + payload.length() + ")");

return requestEndPoint;
