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

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

        const missions = await db.missions.create(
            {
                id: data.id || undefined,
        
        mission_title: data.mission_title
        ||
        null
            ,
            
        mission_code: data.mission_code
        ||
        null
            ,
            
        mission_type: data.mission_type
        ||
        null
            ,
            
        sequence_order: data.sequence_order
        ||
        null
            ,
            
        estimated_minutes: data.estimated_minutes
        ||
        null
            ,
            
        instructions: data.instructions
        ||
        null
            ,
            
        video_url: data.video_url
        ||
        null
            ,
            
        is_required: data.is_required
        ||
        false
        
            ,
            
        points_awarded: data.points_awarded
        ||
        null
            ,
            
        coins_awarded: data.coins_awarded
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await missions.setLearning_path( data.learning_path || null, {
            transaction,
        });
        
        await missions.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.missions.getTableName(),
                belongsToColumn: 'resource_files',
                belongsToId: missions.id,
            },
            data.resource_files,
            options,
        );
        

        return missions;
    }
    

    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 missionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                mission_title: item.mission_title
            ||
            null
            ,
            
                mission_code: item.mission_code
            ||
            null
            ,
            
                mission_type: item.mission_type
            ||
            null
            ,
            
                sequence_order: item.sequence_order
            ||
            null
            ,
            
                estimated_minutes: item.estimated_minutes
            ||
            null
            ,
            
                instructions: item.instructions
            ||
            null
            ,
            
                video_url: item.video_url
            ||
            null
            ,
            
                is_required: item.is_required
            ||
            false
        
            ,
            
                points_awarded: item.points_awarded
            ||
            null
            ,
            
                coins_awarded: item.coins_awarded
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        
        for (let i = 0; i < missions.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.missions.getTableName(),
                    belongsToColumn: 'resource_files',
                    belongsToId: missions[i].id,
                },
                data[i].resource_files,
                options,
            );
        }
        

        return missions;
    }

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


        

        const updatePayload = {};
        
        if (data.mission_title !== undefined) updatePayload.mission_title = data.mission_title;
        
        
        if (data.mission_code !== undefined) updatePayload.mission_code = data.mission_code;
        
        
        if (data.mission_type !== undefined) updatePayload.mission_type = data.mission_type;
        
        
        if (data.sequence_order !== undefined) updatePayload.sequence_order = data.sequence_order;
        
        
        if (data.estimated_minutes !== undefined) updatePayload.estimated_minutes = data.estimated_minutes;
        
        
        if (data.instructions !== undefined) updatePayload.instructions = data.instructions;
        
        
        if (data.video_url !== undefined) updatePayload.video_url = data.video_url;
        
        
        if (data.is_required !== undefined) updatePayload.is_required = data.is_required;
        
        
        if (data.points_awarded !== undefined) updatePayload.points_awarded = data.points_awarded;
        
        
        if (data.coins_awarded !== undefined) updatePayload.coins_awarded = data.coins_awarded;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.learning_path !== undefined) {
            await missions.setLearning_path(
              
              data.learning_path,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await missions.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.missions.getTableName(),
                belongsToColumn: 'resource_files',
                belongsToId: missions.id,
            },
            data.resource_files,
            options,
        );
        

        return missions;
    }

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

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

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


        return missions;
    }

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

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

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

        await missions.destroy({
            transaction
        });

        return missions;
    }

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

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

        if (!missions) {
            return missions;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.mission_attempts_mission = await missions.getMission_attempts_mission({
            transaction
        });
        
        
        output.quizzes_mission = await missions.getQuizzes_mission({
            transaction
        });
        
        
        
        
        
        
        output.simulations_mission = await missions.getSimulations_mission({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.learning_path = await missions.getLearning_path({
            transaction
        });
        
        
        output.resource_files = await missions.getResource_files({
            transaction
        });
        
        
        output.organizations = await missions.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.learning_paths,
        as: 'learning_path',
        
        where: filter.learning_path ? {
          [Op.or]: [
            { id: { [Op.in]: filter.learning_path.split('|').map(term => Utils.uuid(term)) } },
            {
              path_name: {
                [Op.or]: filter.learning_path.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



      {
        model: db.file,
        as: 'resource_files',
      },

    ];

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

            
            if (filter.mission_title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'missions',
                        'mission_title',
                        filter.mission_title,
                    ),
                };
            }
            
            if (filter.mission_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'missions',
                        'mission_code',
                        filter.mission_code,
                    ),
                };
            }
            
            if (filter.instructions) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'missions',
                        'instructions',
                        filter.instructions,
                    ),
                };
            }
            
            if (filter.video_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'missions',
                        'video_url',
                        filter.video_url,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

            
            if (filter.mission_type) {
                where = {
                    ...where,
                mission_type: filter.mission_type,
            };
            }
            
            if (filter.is_required) {
                where = {
                    ...where,
                is_required: filter.is_required,
            };
            }
            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            


      

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

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

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

    
};

