use crate::error::{HermesError, Result};
use reqwest::{multipart, Body, Client};
use std::path::Path;
use tokio::fs::File;
use tokio_util::io::ReaderStream;

/// Uploads a file stream directly from disk to the Hippius Sync-Engine to bypass RAM.
pub async fn upload_file_to_store(
    client: &Client,
    base_url: &str,
    api_token: &str,
    file_path: &str,
) -> Result<String> {
    let path = Path::new(file_path);
    let file = File::open(path).await?;

    // Create a zero-copy byte stream from the file handle using tokio_util
    let stream = ReaderStream::new(file);
    let body = Body::wrap_stream(stream);

    let file_name = path
        .file_name()
        .unwrap_or_default()
        .to_string_lossy()
        .to_string();

    let part = multipart::Part::stream(body).file_name(file_name);
    let form = multipart::Form::new().part("file", part);

    let url = format!("{}/api/upload", base_url.trim_end_matches('/'));
    let res = client
        .post(&url)
        .header("Authorization", format!("Bearer {}", api_token))
        .multipart(form)
        .send()
        .await?;

    let res = res.error_for_status().map_err(HermesError::Http)?;
    let json: serde_json::Value = res.json().await?;

    let hash = json["hash"]
        .as_str()
        .ok_or_else(|| HermesError::Payload("Missing hash in response".into()))?
        .to_string();

    Ok(hash)
}
