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

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

        const matches = await db.matches.create(
            {
                id: data.id || undefined,
        
        game_code: data.game_code
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        is_locked: data.is_locked
        ||
        false
        
            ,
            
        max_players: data.max_players
        ||
        null
            ,
            
        question_count: data.question_count
        ||
        null
            ,
            
        randomize_questions: data.randomize_questions
        ||
        false
        
            ,
            
        randomize_answers: data.randomize_answers
        ||
        false
        
            ,
            
        wheel_event_every_n_questions: data.wheel_event_every_n_questions
        ||
        null
            ,
            
        cat_interaction_every_n_questions: data.cat_interaction_every_n_questions
        ||
        null
            ,
            
        starting_speed_kmh: data.starting_speed_kmh
        ||
        null
            ,
            
        race_map: data.race_map
        ||
        null
            ,
            
        scheduled_start_at: data.scheduled_start_at
        ||
        null
            ,
            
        started_at: data.started_at
        ||
        null
            ,
            
        ended_at: data.ended_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await matches.setHost( data.host || null, {
            transaction,
        });
        
        await matches.setMode( data.mode || null, {
            transaction,
        });
        
        await matches.setQuiz( data.quiz || null, {
            transaction,
        });
        

        

        

        return matches;
    }
    

    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 matchesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                game_code: item.game_code
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                is_locked: item.is_locked
            ||
            false
        
            ,
            
                max_players: item.max_players
            ||
            null
            ,
            
                question_count: item.question_count
            ||
            null
            ,
            
                randomize_questions: item.randomize_questions
            ||
            false
        
            ,
            
                randomize_answers: item.randomize_answers
            ||
            false
        
            ,
            
                wheel_event_every_n_questions: item.wheel_event_every_n_questions
            ||
            null
            ,
            
                cat_interaction_every_n_questions: item.cat_interaction_every_n_questions
            ||
            null
            ,
            
                starting_speed_kmh: item.starting_speed_kmh
            ||
            null
            ,
            
                race_map: item.race_map
            ||
            null
            ,
            
                scheduled_start_at: item.scheduled_start_at
            ||
            null
            ,
            
                started_at: item.started_at
            ||
            null
            ,
            
                ended_at: item.ended_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return matches;
    }

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

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


        

        const updatePayload = {};
        
        if (data.game_code !== undefined) updatePayload.game_code = data.game_code;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.is_locked !== undefined) updatePayload.is_locked = data.is_locked;
        
        
        if (data.max_players !== undefined) updatePayload.max_players = data.max_players;
        
        
        if (data.question_count !== undefined) updatePayload.question_count = data.question_count;
        
        
        if (data.randomize_questions !== undefined) updatePayload.randomize_questions = data.randomize_questions;
        
        
        if (data.randomize_answers !== undefined) updatePayload.randomize_answers = data.randomize_answers;
        
        
        if (data.wheel_event_every_n_questions !== undefined) updatePayload.wheel_event_every_n_questions = data.wheel_event_every_n_questions;
        
        
        if (data.cat_interaction_every_n_questions !== undefined) updatePayload.cat_interaction_every_n_questions = data.cat_interaction_every_n_questions;
        
        
        if (data.starting_speed_kmh !== undefined) updatePayload.starting_speed_kmh = data.starting_speed_kmh;
        
        
        if (data.race_map !== undefined) updatePayload.race_map = data.race_map;
        
        
        if (data.scheduled_start_at !== undefined) updatePayload.scheduled_start_at = data.scheduled_start_at;
        
        
        if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
        
        
        if (data.ended_at !== undefined) updatePayload.ended_at = data.ended_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.host !== undefined) {
            await matches.setHost(
              
              data.host,
              
              { transaction }
            );
        }
        
        if (data.mode !== undefined) {
            await matches.setMode(
              
              data.mode,
              
              { transaction }
            );
        }
        
        if (data.quiz !== undefined) {
            await matches.setQuiz(
              
              data.quiz,
              
              { transaction }
            );
        }
        

        
        

        

        return matches;
    }

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

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

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


        return matches;
    }

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

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

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

        await matches.destroy({
            transaction
        });

        return matches;
    }

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

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

        if (!matches) {
            return matches;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.match_players_match = await matches.getMatch_players_match({
            transaction
        });
        
        
        output.match_questions_match = await matches.getMatch_questions_match({
            transaction
        });
        
        
        
        output.wheel_events_match = await matches.getWheel_events_match({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        output.host = await matches.getHost({
            transaction
        });
        
        
        output.mode = await matches.getMode({
            transaction
        });
        
        
        output.quiz = await matches.getQuiz({
            transaction
        });
        
        

        return output;
    }

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

        

        

        offset = currentPage * limit;

        const orderBy = null;

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

    let include = [

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

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

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



    ];

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

            
            if (filter.game_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'matches',
                        'game_code',
                        filter.game_code,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            
            if (filter.is_locked) {
                where = {
                    ...where,
                is_locked: filter.is_locked,
            };
            }
            
            if (filter.randomize_questions) {
                where = {
                    ...where,
                randomize_questions: filter.randomize_questions,
            };
            }
            
            if (filter.randomize_answers) {
                where = {
                    ...where,
                randomize_answers: filter.randomize_answers,
            };
            }
            
            if (filter.race_map) {
                where = {
                    ...where,
                race_map: filter.race_map,
            };
            }
            


      

      

      



            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,
                        },
                    };
                }
            }
        }
        

        

        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.matches.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, ) {
        let where = {};
        
        

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

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

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

    
};

