use eyre::ContextCompat;
use sea_orm::{ActiveValue::Set, prelude::*};

use crate::{db::entities::key, error::Result};

pub struct KeyTable<'db> {
  db: &'db DatabaseConnection,
}

impl<'db> KeyTable<'db> {
  pub fn new(db: &'db DatabaseConnection) -> Self {
    Self { db }
  }

  pub async fn get_key_by_name(&self, name: String) -> Result<key::Model> {
    let res = key::Entity::find()
      .filter(key::Column::Name.eq(&name))
      .one(self.db)
      .await?;

    Ok(res.context(format!("Key with name {} not found", name))?)
  }

  pub async fn create_key(&self, name: String, key: String, id: Uuid) -> Result<()> {
    let model = key::ActiveModel {
      name: Set(name),
      private_key: Set(key),
      id: Set(id),
    };

    model.insert(self.db).await?;

    Ok(())
  }
}
