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

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

        const match_questions = await db.match_questions.create(
            {
                id: data.id || undefined,
        
        question_index: data.question_index
        ||
        null
            ,
            
        revealed_at: data.revealed_at
        ||
        null
            ,
            
        closed_at: data.closed_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await match_questions.setMatch( data.match || null, {
            transaction,
        });
        
        await match_questions.setQuiz_question( data.quiz_question || null, {
            transaction,
        });
        

        

        

        return match_questions;
    }
    

    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 match_questionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                question_index: item.question_index
            ||
            null
            ,
            
                revealed_at: item.revealed_at
            ||
            null
            ,
            
                closed_at: item.closed_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return match_questions;
    }

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

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


        

        const updatePayload = {};
        
        if (data.question_index !== undefined) updatePayload.question_index = data.question_index;
        
        
        if (data.revealed_at !== undefined) updatePayload.revealed_at = data.revealed_at;
        
        
        if (data.closed_at !== undefined) updatePayload.closed_at = data.closed_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.match !== undefined) {
            await match_questions.setMatch(
              
              data.match,
              
              { transaction }
            );
        }
        
        if (data.quiz_question !== undefined) {
            await match_questions.setQuiz_question(
              
              data.quiz_question,
              
              { transaction }
            );
        }
        

        
        

        

        return match_questions;
    }

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

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

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


        return match_questions;
    }

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

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

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

        await match_questions.destroy({
            transaction
        });

        return match_questions;
    }

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

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

        if (!match_questions) {
            return match_questions;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.player_answers_match_question = await match_questions.getPlayer_answers_match_question({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        output.match = await match_questions.getMatch({
            transaction
        });
        
        
        output.quiz_question = await match_questions.getQuiz_question({
            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.matches,
        as: 'match',
        
        where: filter.match ? {
          [Op.or]: [
            { id: { [Op.in]: filter.match.split('|').map(term => Utils.uuid(term)) } },
            {
              game_code: {
                [Op.or]: filter.match.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

            

            
            

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

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

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

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

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

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

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

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

            


      

      



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

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

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

    
};

