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

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

        const player_answers = await db.player_answers.create(
            {
                id: data.id || undefined,
        
        is_correct: data.is_correct
        ||
        false
        
            ,
            
        points_awarded: data.points_awarded
        ||
        null
            ,
            
        answer_time_ms: data.answer_time_ms
        ||
        null
            ,
            
        answered_at: data.answered_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await player_answers.setMatch_player( data.match_player || null, {
            transaction,
        });
        
        await player_answers.setMatch_question( data.match_question || null, {
            transaction,
        });
        
        await player_answers.setSelected_answer( data.selected_answer || null, {
            transaction,
        });
        

        

        

        return player_answers;
    }
    

    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 player_answersData = data.map((item, index) => ({
                id: item.id || undefined,
                
                is_correct: item.is_correct
            ||
            false
        
            ,
            
                points_awarded: item.points_awarded
            ||
            null
            ,
            
                answer_time_ms: item.answer_time_ms
            ||
            null
            ,
            
                answered_at: item.answered_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return player_answers;
    }

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

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


        

        const updatePayload = {};
        
        if (data.is_correct !== undefined) updatePayload.is_correct = data.is_correct;
        
        
        if (data.points_awarded !== undefined) updatePayload.points_awarded = data.points_awarded;
        
        
        if (data.answer_time_ms !== undefined) updatePayload.answer_time_ms = data.answer_time_ms;
        
        
        if (data.answered_at !== undefined) updatePayload.answered_at = data.answered_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.match_player !== undefined) {
            await player_answers.setMatch_player(
              
              data.match_player,
              
              { transaction }
            );
        }
        
        if (data.match_question !== undefined) {
            await player_answers.setMatch_question(
              
              data.match_question,
              
              { transaction }
            );
        }
        
        if (data.selected_answer !== undefined) {
            await player_answers.setSelected_answer(
              
              data.selected_answer,
              
              { transaction }
            );
        }
        

        
        

        

        return player_answers;
    }

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

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

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


        return player_answers;
    }

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

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

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

        await player_answers.destroy({
            transaction
        });

        return player_answers;
    }

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

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

        if (!player_answers) {
            return player_answers;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.match_player = await player_answers.getMatch_player({
            transaction
        });
        
        
        output.match_question = await player_answers.getMatch_question({
            transaction
        });
        
        
        output.selected_answer = await player_answers.getSelected_answer({
            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.match_players,
        as: 'match_player',
        
        where: filter.match_player ? {
          [Op.or]: [
            { id: { [Op.in]: filter.match_player.split('|').map(term => Utils.uuid(term)) } },
            {
              display_name: {
                [Op.or]: filter.match_player.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



    ];

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

            

            
            

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

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

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

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

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

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

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

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

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


      

      

      



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

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

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

    
};

