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

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

#[derive(Clone, Debug, Identifiable, Insertable, Queryable, Selectable)]
#[diesel(table_name = team_memberships)]
#[diesel(primary_key(team_id, user_id))]
#[diesel(check_for_backend(Pg))]
pub struct TeamMembership {
    pub team_id: Uuid,
    pub user_id: Uuid,
}

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

    #[auto_type(no_type_alias)]
    pub fn with_team_id<'a>(id: &'a Uuid) -> _ {
        team_memberships::team_id.eq(id)
    }

    #[auto_type(no_type_alias)]
    pub fn with_user_id<'a>(id: &'a Uuid) -> _ {
        team_memberships::user_id.eq(id)
    }
}
