use axum::{
    extract::{Query, State},
    response::IntoResponse,
    Json,
};
use reqwest::{header, StatusCode};

use crate::{
    models::{List, Search},
    services,
    sources::manager::SourceManagerHandle,
};

pub async fn fetch_all(State(handles): State<Vec<SourceManagerHandle>>) -> impl IntoResponse {
    match services::list::fetch_all(handles).await {
        Ok(list) => (StatusCode::OK, Json(list)),
        Err(err) => {
            tracing::error!("{err}");
            (StatusCode::INTERNAL_SERVER_ERROR, Json(List::empty()))
        }
    }
}

pub async fn fetch_all_as_mastodon_csv(
    State(handles): State<Vec<SourceManagerHandle>>,
) -> impl IntoResponse {
    match services::list::fetch_all_as_mastodon_csv(handles).await {
        Ok(res) => (StatusCode::OK, [(header::CONTENT_TYPE, "text/csv")], res),
        Err(err) => {
            tracing::error!("{err}");
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                [(header::CONTENT_TYPE, "text/csv")],
                String::new(),
            )
        }
    }
}

pub async fn search_domain(
    State(handles): State<Vec<SourceManagerHandle>>,
    Query(query): Query<Search>,
) -> impl IntoResponse {
    tracing::info!("incoming search request: {query:?}");
    match services::list::search_domain(query, handles).await {
        Ok(list) => (StatusCode::OK, Json(list)),
        Err(err) => {
            tracing::error!("{err}");
            (StatusCode::INTERNAL_SERVER_ERROR, Json(List::empty()))
        }
    }
}
