use crate::config::get_config;
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]
pub struct VideosResponse {
    pub videos: Vec<serde_json::Value>,
    #[serde(rename = "count", default)]
    pub total: i64,
    pub page: usize,
    pub page_size: usize,
}

#[tauri::command]
pub async fn get_videos(
    query: Option<String>,
    status: Option<String>,
    page: Option<usize>,
    page_size: Option<usize>,
) -> Result<VideosResponse, String> {
    let config = get_config();
    let client = reqwest::Client::new();

    let mut url = format!("{}/api/v1/videos", config.api_base_url);
    let mut params = Vec::new();

    if let Some(q) = query {
        params.push(format!("q={}", q));
    }
    if let Some(s) = status {
        params.push(format!("status={}", s));
    }
    if let Some(p) = page {
        params.push(format!("page={}", p));
    }
    if let Some(ps) = page_size {
        params.push(format!("page_size={}", ps));
    }

    if !params.is_empty() {
        url.push('?');
        url.push_str(&params.join("&"));
    }

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

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

    let result: VideosResponse = response
        .json()
        .await
        .map_err(|e| format!("Failed to parse API response: {}", e))?;

    Ok(result)
}

#[tauri::command]
pub async fn list_videos(
    query: Option<String>,
    page: Option<usize>,
    page_size: Option<usize>,
) -> Result<VideosResponse, String> {
    get_videos(query, None, page, page_size).await
}

#[tauri::command]
pub async fn get_video_faces(file_uuid: String) -> Result<serde_json::Value, String> {
    let config = get_config();
    let client = reqwest::Client::new();
    let url = format!("{}/api/v1/videos/{}/faces", config.api_base_url, file_uuid);

    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()));
    }

    response
        .json()
        .await
        .map_err(|e| format!("Failed to parse response: {}", e))
}

#[tauri::command]
pub async fn get_chunk_detail(uuid: String, chunk_id: String) -> Result<serde_json::Value, String> {
    let config = get_config();
    let client = reqwest::Client::new();
    let url = format!(
        "{}/api/v1/videos/{}/details?chunk_id={}",
        config.api_base_url, uuid, chunk_id
    );

    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()));
    }

    response
        .json()
        .await
        .map_err(|e| format!("Failed to parse response: {}", e))
}
