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

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

        const task_submissions = await db.task_submissions.create(
            {
                id: data.id || undefined,
        
        status: data.status
        ||
        null
            ,
            
        submission_text: data.submission_text
        ||
        null
            ,
            
        submission_url: data.submission_url
        ||
        null
            ,
            
        submitted_at: data.submitted_at
        ||
        null
            ,
            
        reviewed_at: data.reviewed_at
        ||
        null
            ,
            
        ai_feedback: data.ai_feedback
        ||
        null
            ,
            
        ai_score: data.ai_score
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await task_submissions.setUser( data.user || null, {
            transaction,
        });
        
        await task_submissions.setBuild_task( data.build_task || null, {
            transaction,
        });
        
        await task_submissions.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

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

        return task_submissions;
    }
    

    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 task_submissionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                status: item.status
            ||
            null
            ,
            
                submission_text: item.submission_text
            ||
            null
            ,
            
                submission_url: item.submission_url
            ||
            null
            ,
            
                submitted_at: item.submitted_at
            ||
            null
            ,
            
                reviewed_at: item.reviewed_at
            ||
            null
            ,
            
                ai_feedback: item.ai_feedback
            ||
            null
            ,
            
                ai_score: item.ai_score
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return task_submissions;
    }

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


        

        const updatePayload = {};
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.submission_text !== undefined) updatePayload.submission_text = data.submission_text;
        
        
        if (data.submission_url !== undefined) updatePayload.submission_url = data.submission_url;
        
        
        if (data.submitted_at !== undefined) updatePayload.submitted_at = data.submitted_at;
        
        
        if (data.reviewed_at !== undefined) updatePayload.reviewed_at = data.reviewed_at;
        
        
        if (data.ai_feedback !== undefined) updatePayload.ai_feedback = data.ai_feedback;
        
        
        if (data.ai_score !== undefined) updatePayload.ai_score = data.ai_score;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.user !== undefined) {
            await task_submissions.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        
        if (data.build_task !== undefined) {
            await task_submissions.setBuild_task(
              
              data.build_task,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await task_submissions.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

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

        return task_submissions;
    }

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

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

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


        return task_submissions;
    }

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

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

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

        await task_submissions.destroy({
            transaction
        });

        return task_submissions;
    }

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

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

        if (!task_submissions) {
            return task_submissions;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await task_submissions.getUser({
            transaction
        });
        
        
        output.build_task = await task_submissions.getBuild_task({
            transaction
        });
        
        
        output.submission_files = await task_submissions.getSubmission_files({
            transaction
        });
        
        
        output.organizations = await task_submissions.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.build_tasks,
        as: 'build_task',
        
        where: filter.build_task ? {
          [Op.or]: [
            { id: { [Op.in]: filter.build_task.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.build_task.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



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

    ];

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

            
            if (filter.submission_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'task_submissions',
                        'submission_text',
                        filter.submission_text,
                    ),
                };
            }
            
            if (filter.submission_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'task_submissions',
                        'submission_url',
                        filter.submission_url,
                    ),
                };
            }
            
            if (filter.ai_feedback) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'task_submissions',
                        'ai_feedback',
                        filter.ai_feedback,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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

    
};

