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

use crate::{
    app_error::AppError, csrf::validate_csrf_token, team_memberships::TeamMembership, teams::Team,
    users::User,
};

pub async fn require_team_membership(
    current_user: &User,
    team_id: &Uuid,
    db_conn: &Connection,
) -> Result<Team, AppError> {
    let current_user_id = current_user.id.clone();
    let team_id = team_id.clone();
    match db_conn
        .interact(move |conn| {
            TeamMembership::all()
                .filter(TeamMembership::with_user_id(current_user_id))
                .filter(TeamMembership::with_team_id(team_id))
                .first(conn)
                .optional()
        })
        .await
        .unwrap()?
    {
        Some((team, _)) => Ok(team),
        None => Err(AppError::ForbiddenError(
            "not a member of requested team".to_string(),
        )),
    }
}

pub async fn require_valid_csrf_token(
    csrf_token: &str,
    current_user: &User,
    db_conn: &Connection,
) -> Result<(), AppError> {
    if validate_csrf_token(db_conn, csrf_token, Some(current_user.id.clone())).await? {
        Ok(())
    } else {
        Err(AppError::ForbiddenError("invalid CSRF token".to_string()))
    }
}
