use crate::config::get_config;
use base64::{engine::general_purpose, Engine as _};

#[tauri::command]
pub async fn get_person_thumbnail(
    person_id: String,
    file_uuid: String,
    index: Option<usize>,
    save_path: String,
) -> Result<String, String> {
    let config = get_config();
    let client = reqwest::Client::new();

    let mut url = format!(
        "{}/api/v1/person/{}/thumbnail?file_uuid={}",
        config.api_base_url, person_id, file_uuid
    );

    if let Some(idx) = index {
        url = format!("{}&index={}", url, idx);
    }

    let response = client
        .get(&url)
        .header("x-api-key", &config.api_key)
        .send()
        .await
        .map_err(|e| format!("Request failed: {}", e))?;

    if !response.status().is_success() {
        return Err(format!("API error: {}", response.status()));
    }

    // Save the image to the specified path
    let bytes = response
        .bytes()
        .await
        .map_err(|e| format!("Failed to read response: {}", e))?;

    tokio::fs::write(&save_path, &bytes)
        .await
        .map_err(|e| format!("Failed to save file: {}", e))?;

    Ok(save_path)
}

/// Get person thumbnail as base64 data URI
#[tauri::command]
pub async fn get_person_thumbnail_b64(
    person_id: String,
    file_uuid: String,
    index: Option<usize>,
) -> Result<String, String> {
    let config = get_config();
    let client = reqwest::Client::new();

    let mut url = format!(
        "{}/api/v1/person/{}/thumbnail?file_uuid={}",
        config.api_base_url, person_id, file_uuid
    );

    if let Some(idx) = index {
        url = format!("{}&index={}", url, idx);
    }

    let response = client
        .get(&url)
        .header("x-api-key", &config.api_key)
        .send()
        .await
        .map_err(|e| format!("Request failed: {}", e))?;

    if !response.status().is_success() {
        return Err(format!("API error: {}", response.status()));
    }

    let bytes = response
        .bytes()
        .await
        .map_err(|e| format!("Failed to read response: {}", e))?;

    let encoded = general_purpose::STANDARD.encode(&bytes);
    Ok(format!("data:image/jpeg;base64,{}", encoded))
}
