use indieweb::http::Client;
use indieweb::standards::indieauth::AccessToken;
use indieweb::standards::micropub::query::{Query, QueryKind, Response, SourceQuery};
use serde::Serialize;
use serde_json::Value;
use url::Url;

#[derive(Serialize)]
pub struct ReadResult {
    pub url: String,
    pub item: Value,
    pub post_type: Option<Vec<String>>,
}

pub async fn run(
    client: &impl Client,
    endpoint: &Url,
    access_token: &AccessToken,
    post_url: &Url,
) -> miette::Result<ReadResult> {
    let source_query = SourceQuery {
        url: Some(post_url.clone()),
        ..Default::default()
    };

    let query = Query {
        pagination: Default::default(),
        kind: QueryKind::Source(Box::new(source_query)),
    };

    let response = query.send(client, endpoint, access_token).await?;

    match response {
        Response::Source(source) => {
            let item_json = serde_json::to_value(&source.item)
                .map_err(|e| miette::miette!("Failed to serialize item: {}", e))?;
            
            Ok(ReadResult {
                url: post_url.to_string(),
                item: item_json,
                post_type: if source.post_type.is_empty() {
                    None
                } else {
                    Some(source.post_type.iter().map(|t| t.to_string()).collect())
                },
            })
        }
        Response::Error(e) => Err(miette::miette!("Micropub error: {:?}", e)),
        _ => Err(miette::miette!("Unexpected response type")),
    }
}
