use crate::controllers::HttpResult;
use crate::extractors::account_extractor::AccountInPath;
use crate::extractors::auth_extractor::AuthExtractor;
use crate::models::accounts::Account;
use crate::services::accounts_service::UpdateAccountQuery;
use crate::services::{accounts_service, movements_service};
use actix_web::{HttpResponse, web};

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

    accounts_service::create(auth.user_id(), &req).await?;

    Ok(HttpResponse::Created().finish())
}

#[derive(serde::Deserialize)]
pub struct GetListQuery {
    #[serde(default)]
    include_balances: bool,
}

#[derive(serde::Serialize)]
struct AccountAndBalance {
    #[serde(flatten)]
    account: Account,
    balance: f32,
}

/// Get the list of accounts of the user
pub async fn get_list(auth: AuthExtractor, query: web::Query<GetListQuery>) -> HttpResult {
    let accounts = accounts_service::get_list_user(auth.user_id()).await?;

    Ok(match query.include_balances {
        false => HttpResponse::Ok().json(accounts),
        true => {
            let balances = movements_service::get_balances(auth.user_id()).await?;
            let accounts = accounts
                .into_iter()
                .map(|account| AccountAndBalance {
                    balance: *balances.get(&account.id()).unwrap_or(&0.0),
                    account,
                })
                .collect::<Vec<_>>();

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

/// Get a single account
pub async fn get_single(account: AccountInPath) -> HttpResult {
    Ok(HttpResponse::Ok().json(account.as_ref()))
}

/// Update an account information
pub async fn update(account: AccountInPath, req: web::Json<UpdateAccountQuery>) -> HttpResult {
    if let Some(err) = req.check_error() {
        return Ok(HttpResponse::BadRequest().json(err));
    }

    accounts_service::update(account.as_ref().id(), &req).await?;

    Ok(HttpResponse::Accepted().finish())
}

/// Set an account as the default one
pub async fn set_default(account: AccountInPath) -> HttpResult {
    accounts_service::set_default(account.as_ref().user_id(), account.as_ref().id()).await?;

    Ok(HttpResponse::Accepted().finish())
}

/// Delete an account
pub async fn delete(account: AccountInPath) -> HttpResult {
    accounts_service::delete(account.as_ref().id()).await?;

    Ok(HttpResponse::Accepted().finish())
}
