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

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

        const attempts = await db.attempts.create(
            {
                id: data.id || undefined,
        
        attempt_kind: data.attempt_kind
        ||
        null
            ,
            
        score: data.score
        ||
        null
            ,
            
        accuracy_percent: data.accuracy_percent
        ||
        null
            ,
            
        duration_seconds: data.duration_seconds
        ||
        null
            ,
            
        result: data.result
        ||
        null
            ,
            
        started_at: data.started_at
        ||
        null
            ,
            
        finished_at: data.finished_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await attempts.setUser( data.user || null, {
            transaction,
        });
        
        await attempts.setExercise( data.exercise || null, {
            transaction,
        });
        
        await attempts.setGame( data.game || null, {
            transaction,
        });
        
        await attempts.setActivity( data.activity || null, {
            transaction,
        });
        
        await attempts.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return attempts;
    }
    

    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 attemptsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                attempt_kind: item.attempt_kind
            ||
            null
            ,
            
                score: item.score
            ||
            null
            ,
            
                accuracy_percent: item.accuracy_percent
            ||
            null
            ,
            
                duration_seconds: item.duration_seconds
            ||
            null
            ,
            
                result: item.result
            ||
            null
            ,
            
                started_at: item.started_at
            ||
            null
            ,
            
                finished_at: item.finished_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return attempts;
    }

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


        

        const updatePayload = {};
        
        if (data.attempt_kind !== undefined) updatePayload.attempt_kind = data.attempt_kind;
        
        
        if (data.score !== undefined) updatePayload.score = data.score;
        
        
        if (data.accuracy_percent !== undefined) updatePayload.accuracy_percent = data.accuracy_percent;
        
        
        if (data.duration_seconds !== undefined) updatePayload.duration_seconds = data.duration_seconds;
        
        
        if (data.result !== undefined) updatePayload.result = data.result;
        
        
        if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
        
        
        if (data.finished_at !== undefined) updatePayload.finished_at = data.finished_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.user !== undefined) {
            await attempts.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        
        if (data.exercise !== undefined) {
            await attempts.setExercise(
              
              data.exercise,
              
              { transaction }
            );
        }
        
        if (data.game !== undefined) {
            await attempts.setGame(
              
              data.game,
              
              { transaction }
            );
        }
        
        if (data.activity !== undefined) {
            await attempts.setActivity(
              
              data.activity,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await attempts.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return attempts;
    }

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

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

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


        return attempts;
    }

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

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

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

        await attempts.destroy({
            transaction
        });

        return attempts;
    }

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

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

        if (!attempts) {
            return attempts;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await attempts.getUser({
            transaction
        });
        
        
        output.exercise = await attempts.getExercise({
            transaction
        });
        
        
        output.game = await attempts.getGame({
            transaction
        });
        
        
        output.activity = await attempts.getActivity({
            transaction
        });
        
        
        output.organizations = await attempts.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.users,
        as: 'user',
        
        where: filter.user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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

      {
        model: db.interactive_activities,
        as: 'activity',
        
        where: filter.activity ? {
          [Op.or]: [
            { id: { [Op.in]: filter.activity.split('|').map(term => Utils.uuid(term)) } },
            {
              title: {
                [Op.or]: filter.activity.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.calendarStart && filter.calendarEnd) {
                where = {
                    ...where,
                    [Op.or]: [
                        {
                            started_at: {
                                [Op.between]: [filter.calendarStart, filter.calendarEnd],
                            },
                    },
                {
                    finished_at: {
                        [Op.between]: [filter.calendarStart, filter.calendarEnd],
                    },
                },
                ],
            };
            }
            

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    duration_seconds: {
                    ...where.duration_seconds,
                            [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.finished_atRange) {
                const [start, end] = filter.finished_atRange;

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

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

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

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


      

      

      

      

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

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

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

    
};

