#[cfg(feature = "server")]
use crate::util::surrealdb::DB;
use serde::{Deserialize, Serialize};

#[cfg(feature = "server")]
mod migration;

#[derive(Debug, Deserialize, Serialize, PartialEq, Eq, Clone)]
pub struct Member {
    pub id: String,
    pub name: Name,
    pub hours: Vec<String>,
    pub groups: Vec<String>,
    pub diploma: Option<String>,
    pub registration_token: Option<String>,
}

#[derive(Debug, Deserialize, Serialize, PartialEq, Eq, Clone)]
pub struct Name {
    pub first: String,
    pub full: String,
}

#[derive(Debug, Deserialize, Serialize, PartialEq, Clone)]
pub struct MembersMigration {
    pub inserted: Vec<Member>,
    pub updated: Vec<Member>,
    pub removed: Vec<Member>,
}

#[cfg(feature = "server")]
impl Member {
    pub async fn fetch_all() -> Result<Vec<Self>, surrealdb::Error> {
        let mut res = DB.query("SELECT record::id(id) as id, name.first, name.full, hours, groups, diploma, registration_token FROM member").await?;

        let members: Vec<Self> = res.take(0)?;

        tracing::info!("{:?}", members);

        Ok(members)
    }

    pub async fn fetch_from_registration_token(
        registration_token: String,
    ) -> Result<Option<Self>, surrealdb::Error> {
        let query = format!("SELECT record::id(id) as id, name.first, name.full, hours, groups, diploma, registration_token FROM ONLY member WHERE registration_token = $registration_token LIMIT 1");

        let mut res = DB
            .query(query)
            .bind(("registration_token", registration_token))
            .await?;

        let member: Option<Self> = res.take(0)?;

        Ok(member)
    }
}

impl MembersMigration {
    pub fn new() -> MembersMigration {
        MembersMigration {
            inserted: vec![],
            updated: vec![],
            removed: vec![],
        }
    }
}
