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

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

        const regulatory_submissions = await db.regulatory_submissions.create(
            {
                id: data.id || undefined,
        
        submission_name: data.submission_name
        ||
        null
            ,
            
        jurisdiction: data.jurisdiction
        ||
        null
            ,
            
        submission_type: data.submission_type
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        planned_submission_at: data.planned_submission_at
        ||
        null
            ,
            
        submitted_at: data.submitted_at
        ||
        null
            ,
            
        decision_at: data.decision_at
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await regulatory_submissions.setProduct( data.product || null, {
            transaction,
        });
        
        await regulatory_submissions.setOwner( data.owner || null, {
            transaction,
        });
        

        

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

        return regulatory_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 regulatory_submissionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                submission_name: item.submission_name
            ||
            null
            ,
            
                jurisdiction: item.jurisdiction
            ||
            null
            ,
            
                submission_type: item.submission_type
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                planned_submission_at: item.planned_submission_at
            ||
            null
            ,
            
                submitted_at: item.submitted_at
            ||
            null
            ,
            
                decision_at: item.decision_at
            ||
            null
            ,
            
                notes: item.notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return regulatory_submissions;
    }

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

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


        

        const updatePayload = {};
        
        if (data.submission_name !== undefined) updatePayload.submission_name = data.submission_name;
        
        
        if (data.jurisdiction !== undefined) updatePayload.jurisdiction = data.jurisdiction;
        
        
        if (data.submission_type !== undefined) updatePayload.submission_type = data.submission_type;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.planned_submission_at !== undefined) updatePayload.planned_submission_at = data.planned_submission_at;
        
        
        if (data.submitted_at !== undefined) updatePayload.submitted_at = data.submitted_at;
        
        
        if (data.decision_at !== undefined) updatePayload.decision_at = data.decision_at;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.product !== undefined) {
            await regulatory_submissions.setProduct(
              
              data.product,
              
              { transaction }
            );
        }
        
        if (data.owner !== undefined) {
            await regulatory_submissions.setOwner(
              
              data.owner,
              
              { transaction }
            );
        }
        

        
        

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

        return regulatory_submissions;
    }

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

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

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


        return regulatory_submissions;
    }

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

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

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

        await regulatory_submissions.destroy({
            transaction
        });

        return regulatory_submissions;
    }

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

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

        if (!regulatory_submissions) {
            return regulatory_submissions;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.product = await regulatory_submissions.getProduct({
            transaction
        });
        
        
        output.owner = await regulatory_submissions.getOwner({
            transaction
        });
        
        
        output.submission_files = await regulatory_submissions.getSubmission_files({
            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.products,
        as: 'product',
        
        where: filter.product ? {
          [Op.or]: [
            { id: { [Op.in]: filter.product.split('|').map(term => Utils.uuid(term)) } },
            {
              product_name: {
                [Op.or]: filter.product.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



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

    ];

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

            
            if (filter.submission_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'regulatory_submissions',
                        'submission_name',
                        filter.submission_name,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'regulatory_submissions',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

            
            if (filter.jurisdiction) {
                where = {
                    ...where,
                jurisdiction: filter.jurisdiction,
            };
            }
            
            if (filter.submission_type) {
                where = {
                    ...where,
                submission_type: filter.submission_type,
            };
            }
            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            


      

      



            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.regulatory_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, ) {
        let where = {};
        
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'regulatory_submissions',
                        'submission_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

