use std::sync::Arc;

use crate::{model::Model, store::Store};

#[derive(Debug)]
pub struct |ControllerNamePascal|Controller {
    store: Arc<dyn Store>,
}

impl |ControllerNamePascal|Controller {
    const TABLE: &'static str = "|controller_name_snake|";

    pub fn new(store: Arc<impl Store>) -> Self {
        |ControllerNamePascal|Controller { store }
    }

    pub async fn create<R>(&self, data: R) -> Option<R>
    where
        R: Model,
    {
        match R::ENTITY {
            Some(id) => self
                .store
                .get_db()
                .create((R::TABLE, id))
                .content(data)
                .await
                .unwrap_or(None),
            None => self
                .store
                .get_db()
                .create(R::TABLE)
                .content(data)
                .await
                .ok()
                .and_then(|mut v| v.pop()),
        }
    }

    pub async fn get<R>(&self, key: &str) -> Option<R>
    where
        R: Model,
    {
        self.store
            .get_db()
            .select((Self::TABLE, key))
            .await
            .unwrap_or(None)
    }
}
