use deadpool_diesel::postgres::Connection;
use diesel::prelude::*;
use uuid::Uuid;

use crate::{app_error::AppError, schema::api_keys::dsl::*, teams::Team};

#[derive(Associations, Clone, Debug, Identifiable, Insertable, Queryable, Selectable)]
#[diesel(table_name = crate::schema::api_keys)]
#[diesel(belongs_to(Team))]
pub struct ApiKey {
    pub id: Uuid,
    pub team_id: Uuid,
}

impl ApiKey {
    pub async fn generate_for_team(
        db_conn: &Connection,
        key_team_id: Uuid,
    ) -> Result<Self, AppError> {
        let api_key = Self {
            id: Uuid::new_v4(),
            team_id: key_team_id,
        };
        let api_key_copy = api_key.clone();
        db_conn
            .interact(move |conn| {
                diesel::insert_into(api_keys)
                    .values(api_key_copy)
                    .execute(conn)
            })
            .await
            .unwrap()?;
        Ok(api_key)
    }
}
