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

use crate::{
    schema::{self, team_memberships::dsl::*},
    teams::Team,
    users::User,
};

#[derive(Associations, Clone, Debug, Identifiable, Insertable, Queryable, Selectable)]
#[diesel(table_name = schema::team_memberships)]
#[diesel(belongs_to(crate::teams::Team))]
#[diesel(belongs_to(crate::users::User))]
#[diesel(primary_key(team_id, user_id))]
#[diesel(check_for_backend(Pg))]
pub struct TeamMembership {
    pub team_id: Uuid,
    pub user_id: Uuid,
    pub roles: Vec<Option<String>>,
}

impl TeamMembership {
    #[diesel::dsl::auto_type(no_type_alias)]
    pub fn all() -> _ {
        let select: AsSelect<(Team, User), Pg> = <(Team, User)>::as_select();
        team_memberships
            .inner_join(schema::teams::table)
            .inner_join(schema::users::table)
            .select(select)
    }

    pub fn with_team_id(team_id_value: Uuid) -> Eq<team_id, Uuid> {
        team_id.eq(team_id_value)
    }

    pub fn with_user_id(user_id_value: Uuid) -> Eq<user_id, Uuid> {
        user_id.eq(user_id_value)
    }
}
