import User from '../models/User.js'
import UserClub from '../models/UserClub.js';
import HttpError from '../exceptions/HttpError.js';

export const getUserByToken = async(token) => {
    try {
        const user = await User.findOne({
            where: [
                {auth_code: token}
            ]
        });
        return user;
    } catch (error) {
        console.log(error);
        const err = new HttpError('noaccess', 403);
        throw err;
    }   
}

export const hasUserClubAccess = async(userId, clubId) => {
    try {
        console.log('[hasUserClubAccess]');
        const userClub = await UserClub.findOne({
            where: {
                user_id: userId,
                club_id: clubId,
                approved: true
            }
        });
        return userClub !== null;
    } catch(error) {
        console.log(error);
        throw new HttpError('notfound', 500);
    }
}

export const checkAccess = async(userToken, clubId) => {
    try {
        const user = await getUserByToken(userToken);
        if (!await hasUserClubAccess(user.id, clubId)) {
            console.log('no club access');
            const err = new HttpError('noaccess', 403);
            throw err;
        }
    } catch (error) {
        console.log(error);
        throw error;        
    }
}