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

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

        const course_phases = await db.course_phases.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        summary: data.summary
        ||
        null
            ,
            
        phase_number: data.phase_number
        ||
        null
            ,
            
        estimated_minutes: data.estimated_minutes
        ||
        null
            ,
            
        unlock_rule: data.unlock_rule
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await course_phases.setCourse( data.course || null, {
            transaction,
        });
        
        await course_phases.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        
        await course_phases.setSkills_awarded(data.skills_awarded || [], {
            transaction,
        });
        

        

        return course_phases;
    }
    

    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 course_phasesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                summary: item.summary
            ||
            null
            ,
            
                phase_number: item.phase_number
            ||
            null
            ,
            
                estimated_minutes: item.estimated_minutes
            ||
            null
            ,
            
                unlock_rule: item.unlock_rule
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return course_phases;
    }

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.summary !== undefined) updatePayload.summary = data.summary;
        
        
        if (data.phase_number !== undefined) updatePayload.phase_number = data.phase_number;
        
        
        if (data.estimated_minutes !== undefined) updatePayload.estimated_minutes = data.estimated_minutes;
        
        
        if (data.unlock_rule !== undefined) updatePayload.unlock_rule = data.unlock_rule;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.course !== undefined) {
            await course_phases.setCourse(
              
              data.course,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await course_phases.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        
        if (data.skills_awarded !== undefined) {
            await course_phases.setSkills_awarded(data.skills_awarded, { transaction });
        }
        

        

        return course_phases;
    }

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

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

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


        return course_phases;
    }

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

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

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

        await course_phases.destroy({
            transaction
        });

        return course_phases;
    }

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

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

        if (!course_phases) {
            return course_phases;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        output.lessons_course_phase = await course_phases.getLessons_course_phase({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.course = await course_phases.getCourse({
            transaction
        });
        
        
        output.skills_awarded = await course_phases.getSkills_awarded({
            transaction
        });
        
        
        output.organizations = await course_phases.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.courses,
        as: 'course',
        
        where: filter.course ? {
          [Op.or]: [
            { id: { [Op.in]: filter.course.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.course.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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


      {
        model: db.skill_nodes,
        as: 'skills_awarded',
        required: false,
      },


    ];

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

            
            if (filter.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'course_phases',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.summary) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'course_phases',
                        'summary',
                        filter.summary,
                    ),
                };
            }
            

            
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    phase_number: {
                    ...where.phase_number,
                            [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.active !== undefined) {
                where = {
                    ...where,
                    active: filter.active === true || filter.active === 'true'
                };
            }

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


      

      
      if (filter.organizations) {
        const listItems = filter.organizations.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          organizationsId: {[Op.or]: listItems}
        };
      }
      


      if (filter.skills_awarded) {
        const searchTerms = filter.skills_awarded.split('|');

        include = [
          {
            model: db.skill_nodes,
            as: 'skills_awarded_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  name: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }


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

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

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

    
};

