// Enable automatic add-on extension
// Required environment: API_ORIGIN, SUBSCRIBER_ACCESS_TOKEN, SIM_ID
// API_ORIGIN is the operator origin, without a /subscriber suffix.
// Edit the illustrative body below or set REQUEST_BODY_FILE to your JSON file.
// Makes one request; does not retry or follow redirects. After an uncertain write, check your order/SIM state before repeating.
// Save in examples/rust/src/bin/sim_plan_sim_enableAutoExtend.rs; run: cargo run --bin sim_plan_sim_enableAutoExtend
// Use the Cargo.toml supplied with these examples.
use std::{env, error::Error, time::Duration};
use reqwest::{blocking::Client, redirect::Policy, Url};
use serde_json::Value;
fn required(name: &str) -> Result<String, Box<dyn Error>> {
    let value = env::var(name).map_err(|_| format!("Set {}", name))?;
    if value.is_empty() { return Err(format!("Set {}", name).into()); }
    Ok(value)
}
fn main() -> Result<(), Box<dyn Error>> {
    let mut url = Url::parse(&required("API_ORIGIN")?)?;
    if !["http", "https"].contains(&url.scheme()) || url.host_str().is_none() || !url.username().is_empty() || url.password().is_some() || url.path() != "/" || url.query().is_some() || url.fragment().is_some() {
        return Err("API_ORIGIN must be an HTTP(S) origin only".into());
    }
    {
        let mut segments = url.path_segments_mut().map_err(|_| "Invalid API_ORIGIN")?;
        segments.clear();
        segments.push("subscriber");
        segments.push("sim");
        segments.push(&required("SIM_ID")?);
        segments.push("plan");
        segments.push("auto_extend");
        segments.push("enable");
    }
    let client = Client::builder().timeout(Duration::from_secs(30)).redirect(Policy::none()).build()?;
    let request = client.request(reqwest::Method::POST, url).bearer_auth(required("SUBSCRIBER_ACCESS_TOKEN")?);
    let example: Value = serde_json::from_str(r###"{
  "smsThreshold": 10,
  "smsAutoExtendAddOnPlanId": "11111111-1111-4111-8111-111111111111"
}"###)?;
    let body = if let Ok(file) = env::var("REQUEST_BODY_FILE") { serde_json::from_str(&std::fs::read_to_string(file)?)? } else { example };
    let request = request.json(&body);
    let response = request.send()?;
    let status = response.status();
    println!("HTTP {}", status.as_u16());
    let text = response.text()?;
    if !text.is_empty() {
        match serde_json::from_str::<Value>(&text) { Ok(value) => println!("{}", serde_json::to_string_pretty(&value)?), Err(_) => println!("{}", text) }
    }
    if !status.is_success() { std::process::exit(1); }
    Ok(())
}
