use crate::controllers::HttpResult;
use crate::extractors::account_extractor::AccountInPath;
use crate::extractors::auth_extractor::AuthExtractor;
use crate::extractors::movement_extractor::MovementInPath;
use crate::services::movements_service;
use crate::services::movements_service::UpdateMovementQuery;
use actix_web::{HttpResponse, web};

/// Create a new movement
pub async fn create(auth: AuthExtractor, req: web::Json<UpdateMovementQuery>) -> HttpResult {
    if let Some(err) = req.check_error(auth.user_id(), None).await? {
        return Ok(HttpResponse::BadRequest().json(err));
    }

    let movement = movements_service::create(&req).await?;

    Ok(HttpResponse::Created().json(movement))
}

/// Get the balances of all the accounts of the user
pub async fn get_accounts_balances(auth: AuthExtractor) -> HttpResult {
    Ok(HttpResponse::Ok().json(movements_service::get_balances(auth.user_id()).await?))
}

/// Select movements filter
#[derive(serde::Deserialize)]
pub struct SelectMovementFilters {
    amount_min: Option<f32>,
    amount_max: Option<f32>,
    time_min: Option<i64>,
    time_max: Option<i64>,
    label: Option<String>,
    limit: Option<usize>,
}

/// Get the list of movements of an account
pub async fn get_list_of_account(
    account_id: AccountInPath,
    query: web::Query<SelectMovementFilters>,
) -> HttpResult {
    let mut list = movements_service::get_list_account(account_id.as_ref().id()).await?;

    if let Some(amount_min) = query.amount_min {
        list.retain(|l| l.amount >= amount_min);
    }

    if let Some(amount_max) = query.amount_max {
        list.retain(|l| l.amount <= amount_max);
    }

    if let Some(time_min) = query.time_min {
        list.retain(|l| l.time >= time_min);
    }

    if let Some(time_max) = query.time_max {
        list.retain(|l| l.time <= time_max);
    }

    if let Some(label) = &query.label {
        list.retain(|l| {
            l.label
                .to_lowercase()
                .contains(label.to_lowercase().as_str())
        });
    }

    if let Some(limit) = query.limit
        && list.len() > limit
    {
        list = list[..limit].to_vec();
    }

    Ok(HttpResponse::Ok().json(list))
}

/// Get a single movement information
pub async fn get_single(movement: MovementInPath) -> HttpResult {
    Ok(HttpResponse::Ok().json(movement.movement()))
}

/// Update a single movement information
pub async fn update(
    auth: AuthExtractor,
    movement: MovementInPath,
    req: web::Json<UpdateMovementQuery>,
) -> HttpResult {
    if let Some(err) = req
        .check_error(auth.user_id(), Some(movement.movement().id()))
        .await?
    {
        return Ok(HttpResponse::BadRequest().json(err));
    }

    movements_service::update(movement.movement().id(), &req).await?;

    Ok(HttpResponse::Ok().json(movements_service::get_by_id(movement.movement().id()).await?))
}

/// Delete a movement
pub async fn delete(movement: MovementInPath) -> HttpResult {
    movements_service::delete(movement.movement().id()).await?;
    Ok(HttpResponse::Accepted().finish())
}
