use cfg_if::cfg_if;
use leptos::*;
use crate::backend::data::{ApiResponse, PwdChange, User, UserProfile};

cfg_if! { if #[cfg(feature = "ssr")] {
    use sqlx::{query_as, Error, PgPool, query};
    use actix_session::*;
    use leptos_actix::{extract, redirect};

    pub async fn has_admin_user(pool: &PgPool) -> Result<bool, Error> {
        let count: (i64,) = query_as(r#"SELECT COUNT(id) FROM "user" WHERE admin = $1"#)
            .bind(true)
            .fetch_one(pool)
            .await?;

        Ok(count.0 > 0)
    }

    pub async fn create_admin(pool: &PgPool) -> Result<(), Error> {
        if !has_admin_user(pool).await? {
            let pwd = pwhash::bcrypt::hash("admin");
            query(r#"INSERT INTO "user"(login, password, full_name, admin) VALUES($1, $2, $3, $4)"#)
                .bind("admin")
                .bind(pwd.unwrap())
                .bind("Admin User")
                .bind(true)
                .execute(pool).await?;
        }

        Ok(())
    }

    pub async fn user_from_login(pool: &PgPool, login: &str) -> Result<User, Error> {
        let usr = query_as::<_, User>(r#"SELECT * FROM "user" WHERE login=$1"#)
            .bind(login)
            .fetch_one(pool).await?;
        Ok(usr)
    }

    pub async fn logged_in_user() -> Option<User> {
        extract(|session: Session| async move {
            session.get::<User>("user").unwrap_or(None)
        }).await.unwrap_or(None)
    }

    pub async fn is_logged_in() -> bool {
        logged_in_user().await.is_some()
    }

    pub async fn is_admin() -> bool {
        if let Some(user) = logged_in_user().await {
            user.admin
        } else {
            false
        }
    }
}}

#[server(Login, "/api")]
pub async fn login(username: String, password: String) -> Result<ApiResponse<()>, ServerFnError> {
    use crate::backend::AppData;
    use actix_session::*;
    use actix_web::web::Data;
    use leptos_actix::extract;
    use actix_web::http::StatusCode;
    use leptos_actix::ResponseOptions;

    let pool = extract(|data: Data<AppData>| async move { data.db_pool().clone() }).await?;

    let user = user_from_login(&pool, &username).await.unwrap_or(User::default());

    if !user.login.is_empty() && pwhash::bcrypt::verify(password, &user.password) {
        extract(|session: Session| async move {
            let _ = session.insert("user", user);
        })
            .await?;

        redirect("/admin");
        return Ok(ApiResponse::Data(()));
    }

    let response = expect_context::<ResponseOptions>();
    response.set_status(StatusCode::UNAUTHORIZED);

    return Ok(ApiResponse::Error("Bad username or password".to_string()))
}

#[server]
pub async fn logout() -> Result<(), ServerFnError> {
    extract(|session: Session| async move {
        session.clear();
    }).await?;

    redirect("/login");
    Ok(())
}

#[server]
pub async fn auth_check() -> Result<bool, ServerFnError> {
    Ok(is_logged_in().await)
}

#[server]
pub async fn admin_check() -> Result<bool, ServerFnError> {
    Ok(is_admin().await)
}

#[server]
pub async fn get_user() -> Result<Option<User>, ServerFnError> {
    Ok(logged_in_user().await)
}

#[server]
pub async fn update_profile(user: UserProfile) -> Result<ApiResponse<()>, ServerFnError> {
    use crate::backend::AppData;
    use actix_web::web::Data;
    use leptos_actix::extract;
    use crate::user_check;

    user_check!(user.login());

    let pool = extract(|data: Data<AppData>| async move { data.db_pool().clone() }).await?;
    sqlx::query(r#"UPDATE "user" SET full_name = $1, email = $2, get_emails = $3 WHERE login = $4"#)
        .bind(user.full_name())
        .bind(user.email())
        .bind(user.get_emails())
        .bind(user.login())
        .execute(&pool)
        .await?;

    let usr = user_from_login(&pool, user.login()).await?;
    extract(|session: Session| async move {
        let _ = session.insert("user", usr);
    }).await?;

    Ok(ApiResponse::Data(()))
}

#[server]
pub async fn change_pwd(new_pw: PwdChange) -> Result<ApiResponse<()>, ServerFnError> {
    use crate::backend::AppData;
    use actix_web::web::Data;
    use leptos_actix::extract;
    use crate::user_check;

    user_check!(new_pw.login());

    let pool = extract(|data: Data<AppData>| async move { data.db_pool().clone() }).await?;
    let usr = user_from_login(&pool, new_pw.login()).await?;

    if !pwhash::bcrypt::verify(new_pw.old_password(), &usr.password) {
        let response = expect_context::<ResponseOptions>();
        response.set_status(StatusCode::UNAUTHORIZED);

        return Ok(ApiResponse::Error("Invalid old password".to_string()))
    }

    sqlx::query(r#"UPDATE "user" SET password = $1 WHERE login = $2"#)
        .bind(pwhash::bcrypt::hash(new_pw.password()).unwrap())
        .bind(new_pw.login())
        .execute(&pool)
        .await?;

    Ok(ApiResponse::Data(()))
}