use crate::creds::Credentials;
use crate::error::Error;
use crate::protocol::query;
use crate::region::Region;
use crate::xml;

const SERVICE: &str = "rds";
const VERSION: &str = "2014-10-31";

pub fn db_instance_endpoint(
    creds: &Credentials,
    region: &Region,
    db_instance_identifier: &str,
) -> Result<String, Error> {
    let xml_body = query::call(
        creds,
        region,
        SERVICE,
        "DescribeDBInstances",
        VERSION,
        &[("DBInstanceIdentifier", db_instance_identifier.to_string())],
    )?;
    parse_db_instance_endpoint(&xml_body, db_instance_identifier)
}

fn parse_db_instance_endpoint(
    xml_body: &str,
    db_instance_identifier: &str,
) -> Result<String, Error> {
    let instances = xml::inner(xml_body, "DBInstances").unwrap_or("");
    let first = xml::inner(instances, "DBInstance").ok_or_else(|| {
        Error::parse(format!(
            "db instance `{db_instance_identifier}` not found in response"
        ))
    })?;
    let endpoint = xml::inner(first, "Endpoint")
        .ok_or_else(|| Error::parse("db instance has no Endpoint (not yet available?)"))?;
    let address =
        xml::inner(endpoint, "Address").ok_or_else(|| Error::parse("Endpoint missing Address"))?;
    Ok(xml::unescape(address))
}
