use cfg_if::cfg_if;

pub mod data;
pub mod company;
pub mod user;
pub mod auth_middleware;

#[macro_export]
macro_rules! perm_check {
    ($check:ident) => {
        use crate::backend::user::$check;
        use actix_web::http::StatusCode;
        use leptos_actix::ResponseOptions;

        if !$check().await {
            let response = expect_context::<ResponseOptions>();
            response.set_status(StatusCode::FORBIDDEN);

            return Ok(ApiResponse::Error("Forbidden".to_string()))
        }
    }
}

#[macro_export]
macro_rules! user_check {
    ($check:expr) => {
        use crate::perm_check;
        use crate::backend::user::logged_in_user;

        perm_check!(is_logged_in);

        if logged_in_user().await.unwrap_or(User::default()).login != $check {
            let response = expect_context::<ResponseOptions>();
            response.set_status(StatusCode::FORBIDDEN);

            return Ok(ApiResponse::Error("You can change your own profile only".to_string()))
        }
    }
}

cfg_if!{
    if #[cfg(feature = "ssr")] {
        use sqlx::PgPool;

        #[derive(Clone)]
        pub struct AppData {
            db_pool: PgPool
        }

        impl AppData {
            pub fn new(db_pool: PgPool) -> Self {
                Self {
                    db_pool
                }
            }

            pub fn db_pool(&self) -> &PgPool {
                &self.db_pool
            }
        }
    }
}