use actix_web::{get, web, HttpResponse, HttpRequest};
use serde::Serialize;
use sqlx::PgPool;
use crate::error::AppError;
use bigdecimal::BigDecimal;
use chrono::NaiveDateTime;
use crate::auth::validate_token;
use crate::models::{OrderItem, OrderWithItems};

#[get("/api/order-history")]
pub async fn get_order_history(
    req: HttpRequest,
    pool: web::Data<PgPool>,
) -> Result<HttpResponse, AppError> {
    let user_id = validate_token(&req).await?;

    let orders = sqlx::query!(
        r#"
        SELECT
            z.id as "id!",
            z.data_zamowienia as "data_zamowienia!",
            z.suma_totalna as "suma_totalna!",
            z.status,
            pz.ilosc as "ilosc!",
            pz.cena as "item_price!",
            k.tytul as "tytul!",
            k.autor as "autor!"
        FROM zamowienia z
        JOIN pozycje_zamowienia pz ON z.id = pz.zamowienie_id
        JOIN ksiazki k ON pz.book_id = k.id
        WHERE z.user_id = $1
        ORDER BY z.id DESC, k.tytul ASC
        "#,
        user_id
    )
    .fetch_all(pool.get_ref())
    .await
    .map_err(|_| AppError::InternalServerError("Błąd serwera".to_string()))?;

    let mut grouped_orders: std::collections::HashMap<i32, OrderWithItems> = std::collections::HashMap::new();
    for record in orders {
        let entry = grouped_orders.entry(record.id).or_insert(OrderWithItems {
            id: record.id,
            data_zamowienia: record.data_zamowienia,
            suma_totalna: record.suma_totalna,
            status: record.status,
            items: Vec::new(),
        });

        entry.items.push(OrderItem {
            tytul: record.tytul,
            autor: record.autor,
            ilosc: record.ilosc,
            cena: record.item_price,
        });
    }

    let result: Vec<OrderWithItems> = grouped_orders.into_values().collect();
    Ok(HttpResponse::Ok().json(result))
}

