
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 GamesDBApi {
    

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

        const games = await db.games.create(
            {
                id: data.id || undefined,
        
        title: data.title
        ||
        null
            ,
            
        game_type: data.game_type
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        start_at: data.start_at
        ||
        null
            ,
            
        end_at: data.end_at
        ||
        null
            ,
            
        target_headcount: data.target_headcount
        ||
        null
            ,
            
        team_count: data.team_count
        ||
        null
            ,
            
        field_cost: data.field_cost
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
        messenger_broadcast_sent: data.messenger_broadcast_sent
        ||
        false
        
            ,
            
        finalized_at: data.finalized_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await games.setClub( data.club || null, {
            transaction,
        });
        
        await games.setLeague( data.league || null, {
            transaction,
        });
        
        await games.setVenue( data.venue || null, {
            transaction,
        });
        
        await games.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return games;
    }
    

    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 gamesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                title: item.title
            ||
            null
            ,
            
                game_type: item.game_type
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                start_at: item.start_at
            ||
            null
            ,
            
                end_at: item.end_at
            ||
            null
            ,
            
                target_headcount: item.target_headcount
            ||
            null
            ,
            
                team_count: item.team_count
            ||
            null
            ,
            
                field_cost: item.field_cost
            ||
            null
            ,
            
                notes: item.notes
            ||
            null
            ,
            
                messenger_broadcast_sent: item.messenger_broadcast_sent
            ||
            false
        
            ,
            
                finalized_at: item.finalized_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return games;
    }

    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 games = await db.games.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.title !== undefined) updatePayload.title = data.title;
        
        
        if (data.game_type !== undefined) updatePayload.game_type = data.game_type;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.start_at !== undefined) updatePayload.start_at = data.start_at;
        
        
        if (data.end_at !== undefined) updatePayload.end_at = data.end_at;
        
        
        if (data.target_headcount !== undefined) updatePayload.target_headcount = data.target_headcount;
        
        
        if (data.team_count !== undefined) updatePayload.team_count = data.team_count;
        
        
        if (data.field_cost !== undefined) updatePayload.field_cost = data.field_cost;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        if (data.messenger_broadcast_sent !== undefined) updatePayload.messenger_broadcast_sent = data.messenger_broadcast_sent;
        
        
        if (data.finalized_at !== undefined) updatePayload.finalized_at = data.finalized_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.club !== undefined) {
            await games.setClub(
              
              data.club,
              
              { transaction }
            );
        }
        
        if (data.league !== undefined) {
            await games.setLeague(
              
              data.league,
              
              { transaction }
            );
        }
        
        if (data.venue !== undefined) {
            await games.setVenue(
              
              data.venue,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await games.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return games;
    }

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

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

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


        return games;
    }

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

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

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

        await games.destroy({
            transaction
        });

        return games;
    }

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

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

        if (!games) {
            return games;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.game_rsvps_game = await games.getGame_rsvps_game({
            transaction
        });
        
        
        output.game_guests_game = await games.getGame_guests_game({
            transaction
        });
        
        
        output.game_teams_game = await games.getGame_teams_game({
            transaction
        });
        
        
        
        output.game_attendances_game = await games.getGame_attendances_game({
            transaction
        });
        
        
        output.game_player_stats_game = await games.getGame_player_stats_game({
            transaction
        });
        
        
        output.game_payments_game = await games.getGame_payments_game({
            transaction
        });
        
        
        
        
        
        
        
        
        output.club = await games.getClub({
            transaction
        });
        
        
        output.league = await games.getLeague({
            transaction
        });
        
        
        output.venue = await games.getVenue({
            transaction
        });
        
        
        output.organizations = await games.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.clubs,
        as: 'club',
        
        where: filter.club ? {
          [Op.or]: [
            { id: { [Op.in]: filter.club.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.club.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.leagues,
        as: 'league',
        
        where: filter.league ? {
          [Op.or]: [
            { id: { [Op.in]: filter.league.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.league.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.venues,
        as: 'venue',
        
        where: filter.venue ? {
          [Op.or]: [
            { id: { [Op.in]: filter.venue.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.venue.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

            
            if (filter.title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'games',
                        'title',
                        filter.title,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'games',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            
            if (filter.calendarStart && filter.calendarEnd) {
                where = {
                    ...where,
                    [Op.or]: [
                        {
                            start_at: {
                                [Op.between]: [filter.calendarStart, filter.calendarEnd],
                            },
                    },
                {
                    end_at: {
                        [Op.between]: [filter.calendarStart, filter.calendarEnd],
                    },
                },
                ],
            };
            }
            

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
            if (filter.game_type) {
                where = {
                    ...where,
                game_type: filter.game_type,
            };
            }
            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            
            if (filter.messenger_broadcast_sent) {
                where = {
                    ...where,
                messenger_broadcast_sent: filter.messenger_broadcast_sent,
            };
            }
            


      

      

      

      
      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.games.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(
                        'games',
                        'title',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

