import Club from '../models/Club.js';
import UserClub from '../models/UserClub.js';
import User from '../models/User.js';
import Member from '../models/Member.js';
import { Op, fn, where, col } from 'sequelize';
import { checkAccess } from '../utils/userUtils.js';

class ClubService {
    async getAllClubs() { 
        return await Club.findAll();
    }

    async findClubByName(clubName) {
        return await Club.findOne({
            where: where(fn('LOWER', col('name')), 'LIKE', `%${clubName.toLowerCase()}%`)
        });
    }

    async createClub(clubName) {
        return await Club.create({ name: clubName });
    }

    async addUserToClub(userId, clubId) {
        return await UserClub.create({ userId: userId, clubId: clubId, approved: true });
    }

    async getUserClubAccess(userId, clubId) {
        return await UserClub.findAll({
            where: {
                userId: userId,
                clubId: clubId,
            }
        });
    }

    async findClubById(clubId) {
        return await Club.findByPk(clubId, {
            include: [
                {
                    model: Member,
                    as: 'members',
                    order: [
                        ['lastName', 'ASC'],  // Sortiere nach Nachname aufsteigend
                        ['firstName', 'ASC']  // Sortiere nach Vorname aufsteigend
                    ],
                },
                {
                    model: User,
                    as: 'Users',
                    through: {
                        attributes: []
                    }
                }
            ]
        });
    }

    async approveUserClubAccess(userToken, clubId, toApproveUserId) {
        await checkAccess(userToken, clubId);
        const toApproveUserClub = await UserClub.findOne({
            where: {
                userId: toApproveUserId,
                clubId: clubId
            }
        });
        if (!toApproveUserClub) {
            throw new Error('norequest');
        }
        return await toApproveUserClub.update({ approved: true });
    }

    async requestAccessToClub(userId, clubId) {
        const access = await UserClub.findAll({
            where: {
                userId: userId,
                clubId: clubId,
            }
        });
        if (access.length > 0) {
            throw new Error('alreadyrequested');
        }
        const club = await Club.findOne({
            where: {
                id: clubId
            }
        });
        if (!club) {
            throw new Error('clubnotfound');
        }
        return await UserClub.create({
            userId: userId,
            clubId: clubId,
            approved: 0
        });
    }

    async getPendingUserApprovals(userToken, clubId) {
        await checkAccess(userToken, clubId);
        return await UserClub.findAll({
            where: {
                clubId: clubId,
                approved: 0
            },
            include: [
                {
                    model: User,
                    as: 'user',
                }
            ]
        });
    }

    async rejectUserClubAccess(userToken, clubId, toRejectUserId) {
        await checkAccess(userToken, clubId);
        const toRejectUserClub = await UserClub.findOne({
            where: {
                userId: toRejectUserId,
                clubId: clubId
            }
        });
        if (!toRejectUserClub) {
            throw new Error('norequest');
        }
        return await toRejectUserClub.destroy();
    }
}

export default new ClubService();
