
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');



const Sequelize = db.Sequelize;
const Op = Sequelize.Op;

module.exports = class ClubsDBApi {
    

    
    static async create(data, options) {
        const currentUser = (options && options.currentUser) || { id: null };
        const transaction = (options && options.transaction) || undefined;

        const clubs = await db.clubs.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        slug: data.slug
        ||
        null
            ,
            
        city: data.city
        ||
        null
            ,
            
        country: data.country
        ||
        null
            ,
            
        default_language: data.default_language
        ||
        null
            ,
            
        default_target_headcount: data.default_target_headcount
        ||
        null
            ,
            
        payment_reminder_days: data.payment_reminder_days
        ||
        null
            ,
            
        inactive_nudge_last_games: data.inactive_nudge_last_games
        ||
        null
            ,
            
        messenger_group_thread: data.messenger_group_thread
        ||
        null
            ,
            
        messenger_access_token: data.messenger_access_token
        ||
        null
            ,
            
        stripe_account_reference: data.stripe_account_reference
        ||
        null
            ,
            
        stripe_connected: data.stripe_connected
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await clubs.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.clubs.getTableName(),
                belongsToColumn: 'logo',
                belongsToId: clubs.id,
            },
            data.logo,
            options,
        );
        

        return clubs;
    }
    

    static async bulkImport(data, options) {
        const currentUser = (options && options.currentUser) || { id: null };
        const transaction = (options && options.transaction) || undefined;

        // Prepare data - wrapping individual data transformations in a map() method
        const clubsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                slug: item.slug
            ||
            null
            ,
            
                city: item.city
            ||
            null
            ,
            
                country: item.country
            ||
            null
            ,
            
                default_language: item.default_language
            ||
            null
            ,
            
                default_target_headcount: item.default_target_headcount
            ||
            null
            ,
            
                payment_reminder_days: item.payment_reminder_days
            ||
            null
            ,
            
                inactive_nudge_last_games: item.inactive_nudge_last_games
            ||
            null
            ,
            
                messenger_group_thread: item.messenger_group_thread
            ||
            null
            ,
            
                messenger_access_token: item.messenger_access_token
            ||
            null
            ,
            
                stripe_account_reference: item.stripe_account_reference
            ||
            null
            ,
            
                stripe_connected: item.stripe_connected
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

        // Bulk create items
        const clubs = await db.clubs.bulkCreate(clubsData, { transaction });

        // For each item created, replace relation files
        
        for (let i = 0; i < clubs.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.clubs.getTableName(),
                    belongsToColumn: 'logo',
                    belongsToId: clubs[i].id,
                },
                data[i].logo,
                options,
            );
        }
        

        return clubs;
    }

    static async update(id, data,  options) {
        const currentUser = (options && options.currentUser) || {id: null};
        const transaction = (options && options.transaction) || undefined;
        const globalAccess = currentUser.app_role?.globalAccess;

        const clubs = await db.clubs.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.slug !== undefined) updatePayload.slug = data.slug;
        
        
        if (data.city !== undefined) updatePayload.city = data.city;
        
        
        if (data.country !== undefined) updatePayload.country = data.country;
        
        
        if (data.default_language !== undefined) updatePayload.default_language = data.default_language;
        
        
        if (data.default_target_headcount !== undefined) updatePayload.default_target_headcount = data.default_target_headcount;
        
        
        if (data.payment_reminder_days !== undefined) updatePayload.payment_reminder_days = data.payment_reminder_days;
        
        
        if (data.inactive_nudge_last_games !== undefined) updatePayload.inactive_nudge_last_games = data.inactive_nudge_last_games;
        
        
        if (data.messenger_group_thread !== undefined) updatePayload.messenger_group_thread = data.messenger_group_thread;
        
        
        if (data.messenger_access_token !== undefined) updatePayload.messenger_access_token = data.messenger_access_token;
        
        
        if (data.stripe_account_reference !== undefined) updatePayload.stripe_account_reference = data.stripe_account_reference;
        
        
        if (data.stripe_connected !== undefined) updatePayload.stripe_connected = data.stripe_connected;
        
        
        updatePayload.updatedById = currentUser.id;

        await clubs.update(updatePayload, {transaction});

        
        
        if (data.organizations !== undefined) {
            await clubs.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.clubs.getTableName(),
                belongsToColumn: 'logo',
                belongsToId: clubs.id,
            },
            data.logo,
            options,
        );
        

        return clubs;
    }

    static async deleteByIds(ids, options) {
        const currentUser = (options && options.currentUser) || { id: null };
        const transaction = (options && options.transaction) || undefined;

        const clubs = await db.clubs.findAll({
            where: {
                id: {
                    [Op.in]: ids,
                },
            },
            transaction,
        });

        await db.sequelize.transaction(async (transaction) => {
            for (const record of clubs) {
                await record.update(
                    {deletedBy: currentUser.id},
                    {transaction}
                );
            }
            for (const record of clubs) {
                await record.destroy({transaction});
            }
        });


        return clubs;
    }

    static async remove(id, options) {
        const currentUser = (options && options.currentUser) || {id: null};
        const transaction = (options && options.transaction) || undefined;

        const clubs = await db.clubs.findByPk(id, options);

        await clubs.update({
            deletedBy: currentUser.id
        }, {
            transaction,
        });

        await clubs.destroy({
            transaction
        });

        return clubs;
    }

    static async findBy(where, options) {
        const transaction = (options && options.transaction) || undefined;

        const clubs = await db.clubs.findOne(
            { where },
            { transaction },
        );

        if (!clubs) {
            return clubs;
        }

        const output = clubs.get({plain: true});

        
        
        
        
        
        
        output.club_memberships_club = await clubs.getClub_memberships_club({
            transaction
        });
        
        
        output.players_club = await clubs.getPlayers_club({
            transaction
        });
        
        
        output.seed_votes_club = await clubs.getSeed_votes_club({
            transaction
        });
        
        
        output.venues_club = await clubs.getVenues_club({
            transaction
        });
        
        
        output.leagues_club = await clubs.getLeagues_club({
            transaction
        });
        
        
        
        
        output.games_club = await clubs.getGames_club({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        output.notifications_club = await clubs.getNotifications_club({
            transaction
        });
        
        
        output.audit_events_club = await clubs.getAudit_events_club({
            transaction
        });
        
        
        
        output.logo = await clubs.getLogo({
            transaction
        });
        
        
        output.organizations = await clubs.getOrganizations({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           globalAccess,  options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        
        const user = (options && options.currentUser) || null;
        const userOrganizations = (user && user.organizations?.id) || null;
        

        
        if (userOrganizations) {
            if (options?.currentUser?.organizationsId) {
                where.organizationsId = options.currentUser.organizationsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

      {
        model: db.organizations,
        as: 'organizations',
        
      },



      {
        model: db.file,
        as: 'logo',
      },

    ];

        if (filter) {
            if (filter.id) {
                where = {
                    ...where,
                    ['id']: Utils.uuid(filter.id),
                };
            }

            
            if (filter.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'clubs',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.slug) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'clubs',
                        'slug',
                        filter.slug,
                    ),
                };
            }
            
            if (filter.city) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'clubs',
                        'city',
                        filter.city,
                    ),
                };
            }
            
            if (filter.country) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'clubs',
                        'country',
                        filter.country,
                    ),
                };
            }
            
            if (filter.messenger_group_thread) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'clubs',
                        'messenger_group_thread',
                        filter.messenger_group_thread,
                    ),
                };
            }
            
            if (filter.messenger_access_token) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'clubs',
                        'messenger_access_token',
                        filter.messenger_access_token,
                    ),
                };
            }
            
            if (filter.stripe_account_reference) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'clubs',
                        'stripe_account_reference',
                        filter.stripe_account_reference,
                    ),
                };
            }
            

            
            

            
            if (filter.default_target_headcountRange) {
                const [start, end] = filter.default_target_headcountRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                    default_target_headcount: {
                    ...where.default_target_headcount,
                            [Op.gte]: start,
                    },
                };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    default_target_headcount: {
                    ...where.default_target_headcount,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.payment_reminder_daysRange) {
                const [start, end] = filter.payment_reminder_daysRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                    payment_reminder_days: {
                    ...where.payment_reminder_days,
                            [Op.gte]: start,
                    },
                };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    payment_reminder_days: {
                    ...where.payment_reminder_days,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.inactive_nudge_last_gamesRange) {
                const [start, end] = filter.inactive_nudge_last_gamesRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                    inactive_nudge_last_games: {
                    ...where.inactive_nudge_last_games,
                            [Op.gte]: start,
                    },
                };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    inactive_nudge_last_games: {
                    ...where.inactive_nudge_last_games,
                            [Op.lte]: end,
                    },
                };
                }
            }
            

            if (filter.active !== undefined) {
                where = {
                    ...where,
                    active: filter.active === true || filter.active === 'true'
                };
            }

            
            if (filter.default_language) {
                where = {
                    ...where,
                default_language: filter.default_language,
            };
            }
            
            if (filter.stripe_connected) {
                where = {
                    ...where,
                stripe_connected: filter.stripe_connected,
            };
            }
            


      
      if (filter.organizations) {
        const listItems = filter.organizations.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          organizationsId: {[Op.or]: listItems}
        };
      }
      



            if (filter.createdAtRange) {
                const [start, end] = filter.createdAtRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                        ['createdAt']: {
                            ...where.createdAt,
                            [Op.gte]: start,
                        },
                    };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                        ['createdAt']: {
                            ...where.createdAt,
                            [Op.lte]: end,
                        },
                    };
                }
            }
        }
        

        
        if (globalAccess) {
            delete where.organizationsId;
        }
        

        const queryOptions = {
            where,
            include,
            distinct: true,
            order: filter.field && filter.sort
                ? [[filter.field, filter.sort]]
                : [['createdAt', 'desc']],
            transaction: options?.transaction,
            logging: console.log
        };

        if (!options?.countOnly) {
            queryOptions.limit = limit ? Number(limit) : undefined;
            queryOptions.offset = offset ? Number(offset) : undefined;
        }

        try {
            const { rows, count } = await db.clubs.findAndCountAll(queryOptions);

            return {
                rows: options?.countOnly ? [] : rows,
                count: count
            };
        } catch (error) {
            console.error('Error executing query:', error);
            throw error;
        }
    }

    static async findAllAutocomplete(query, limit, offset,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'clubs',
                        'name',
                        query,
                    ),
                ],
            };
        }

        const records = await db.clubs.findAll({
            attributes: [ 'id', 'name' ],
            where,
            limit: limit ? Number(limit) : undefined,
            offset: offset ? Number(offset) : undefined,
            orderBy: [['name', 'ASC']],
        });

        return records.map((record) => ({
            id: record.id,
            label: record.name,
        }));
    }

    
};

