use leptos::*;
use crate::backend::data::{ApiResponse, Company};

#[server(GetCompany, "/api", "Url", "get_company")]
pub async fn get_company() -> Result<ApiResponse<Company>, ServerFnError> {
    use crate::backend::AppData;
    use actix_web::web::Data;
    use leptos_actix::extract;
    use crate::perm_check;

    perm_check!(is_logged_in);

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

    let cmp = sqlx::query_as::<_, Company>("SELECT * FROM company")
        .fetch_one(&pool)
        .await?;

    Ok(ApiResponse::Data(cmp))
}

#[server(UpdateCompany, "/api", "Url", "update_company")]
pub async fn update_company(company: Company) -> Result<ApiResponse<()>, ServerFnError> {
    use crate::backend::AppData;
    use actix_web::web::Data;
    use leptos_actix::extract;
    use crate::perm_check;

    perm_check!(is_admin);

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

    sqlx::query(
        "UPDATE company SET name = $1, street = $2, house_number = $3, zip_code = $4, city = $5 \
        WHERE id = $6")
    .bind(company.name.clone())
    .bind(company.street.clone())
    .bind(company.house_number.clone())
    .bind(company.zip_code.clone())
    .bind(company.city.clone())
    .bind(company.id())
    .execute(&pool)
    .await?;

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