use diesel::{
    dsl::{auto_type, AsSelect, Eq},
    pg::Pg,
    prelude::*,
};
use uuid::Uuid;

use crate::{
    api_keys::ApiKey,
    schema::{api_keys, teams},
};

#[derive(Clone, Debug, Identifiable, Insertable, Queryable, Selectable)]
#[diesel(table_name = teams)]
#[diesel(check_for_backend(Pg))]
pub struct Team {
    pub id: Uuid,
    pub name: String,
}

impl Team {
    #[auto_type(no_type_alias)]
    pub fn all() -> _ {
        let select: AsSelect<Team, Pg> = Team::as_select();
        teams::table.select(select)
    }

    #[auto_type(no_type_alias)]
    pub fn api_keys(self) -> _ {
        let all: diesel::dsl::Select<api_keys::table, AsSelect<ApiKey, Pg>> = ApiKey::all();
        let id: Uuid = self.id;
        let filter: Eq<api_keys::team_id, Uuid> = ApiKey::with_team(id);
        all.filter(filter)
    }
}
