use actix_web::{get, web, HttpResponse, Responder};
use crate::models::Book;
use sqlx::PgPool;
use std::collections::HashMap;

#[get("/api/ksiazki")]
pub async fn get_books(
    pool: web::Data<PgPool>,
    query: web::Query<HashMap<String, String>>,
) -> impl Responder {
    let search_term = query.get("search").map(|s| s.as_str()).unwrap_or("");
    let sort_by = query.get("sort").map(|s| s.as_str()).unwrap_or("default");

    let mut base_query = "SELECT id, tytul, autor, cena, COALESCE('/images/' || obraz_url, '/images/placeholder.jpg') as obraz_url, COALESCE(opis, 'Brak opisu') as opis FROM ksiazki".to_string();

    let where_clause = if !search_term.is_empty() {
        " WHERE LOWER(tytul) LIKE LOWER($1) OR LOWER(autor) LIKE LOWER($1)"
    } else {
        ""
    };

    let order_clause = match sort_by {
        "price_asc" => " ORDER BY cena ASC",
        "price_desc" => " ORDER BY cena DESC",
        "title_asc" => " ORDER BY tytul ASC",
        "author_asc" => " ORDER BY autor ASC",
        _ => " ORDER BY tytul ASC",
    };

    let query_str = format!("{}{}{}", base_query, where_clause, order_clause);

    let mut query_builder = sqlx::query_as::<_, Book>(&query_str);

    if !search_term.is_empty() {
        query_builder = query_builder.bind(format!("%{}%", search_term));
    }

    match query_builder.fetch_all(pool.get_ref()).await {
        Ok(books) => HttpResponse::Ok().json(books),
        Err(_) => HttpResponse::InternalServerError().body("Błąd serwera"),
    }
}

#[get("/api/ksiazki/{id}")]
pub async fn get_book(
    pool: web::Data<PgPool>,
    path: web::Path<i32>,
) -> impl Responder {
    let id = path.into_inner();

    match sqlx::query_as!(
        Book,
        r#"
        SELECT id, tytul, autor, cena, COALESCE('/images/' || obraz_url, '/images/placeholder.jpg') as obraz_url, COALESCE(opis, 'Brak opisu') as opis
        FROM ksiazki
        WHERE id = $1
        "#,
        id
    )
    .fetch_optional(pool.get_ref())
    .await {
        Ok(Some(book)) => HttpResponse::Ok().json(book),
        Ok(None) => HttpResponse::NotFound().body("Książka nie znaleziona"),
        Err(_) => HttpResponse::InternalServerError().body("Błąd serwera"),
    }
}

