use crate::terminal::FilingRef;

use super::super::client::SecEdgarClient;
use super::super::service::EdgarLookupError;
use super::super::xbrl::pick_instance_document;
use super::facts::{parse_filing_xbrl_instance, FilingXbrlDocument};

#[derive(Debug, Clone)]
pub(crate) struct FilingPackage {
    pub document: FilingXbrlDocument,
}

pub(crate) async fn load_filing_package(
    client: &SecEdgarClient,
    cik: &str,
    filing: &FilingRef,
) -> Result<FilingPackage, EdgarLookupError> {
    let index = client
        .load_filing_index(cik, &filing.accession_number)
        .await?;
    let filenames = index
        .directory
        .item
        .into_iter()
        .map(|item| item.name)
        .collect::<Vec<_>>();
    let filename =
        pick_instance_document(&filenames).ok_or_else(|| EdgarLookupError::InvalidResponse {
            provider: "SEC EDGAR",
            detail: format!(
                "No XBRL instance document was published for accession {}.",
                filing.accession_number
            ),
        })?;
    let bytes = client
        .load_instance_xml(cik, &filing.accession_number, &filename)
        .await?;
    let document = parse_filing_xbrl_instance(&bytes)?;

    Ok(FilingPackage { document })
}
