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

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

        const contract_folders = await db.contract_folders.create(
            {
                id: data.id || undefined,
        
        title: data.title
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        started_at: data.started_at
        ||
        null
            ,
            
        deadline_at: data.deadline_at
        ||
        null
            ,
            
        completed_at: data.completed_at
        ||
        null
            ,
            
        requires_notary: data.requires_notary
        ||
        false
        
            ,
            
        service_warning: data.service_warning
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await contract_folders.setTenant( data.tenant || null, {
            transaction,
        });
        
        await contract_folders.setCreated_by_user( data.created_by_user || null, {
            transaction,
        });
        
        await contract_folders.setService_type( data.service_type || null, {
            transaction,
        });
        
        await contract_folders.setWorkflow_definition( data.workflow_definition || null, {
            transaction,
        });
        
        await contract_folders.setDocument_template( data.document_template || null, {
            transaction,
        });
        
        await contract_folders.setLocation( data.location || null, {
            transaction,
        });
        
        await contract_folders.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return contract_folders;
    }
    

    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 contract_foldersData = data.map((item, index) => ({
                id: item.id || undefined,
                
                title: item.title
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                started_at: item.started_at
            ||
            null
            ,
            
                deadline_at: item.deadline_at
            ||
            null
            ,
            
                completed_at: item.completed_at
            ||
            null
            ,
            
                requires_notary: item.requires_notary
            ||
            false
        
            ,
            
                service_warning: item.service_warning
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return contract_folders;
    }

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


        

        const updatePayload = {};
        
        if (data.title !== undefined) updatePayload.title = data.title;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
        
        
        if (data.deadline_at !== undefined) updatePayload.deadline_at = data.deadline_at;
        
        
        if (data.completed_at !== undefined) updatePayload.completed_at = data.completed_at;
        
        
        if (data.requires_notary !== undefined) updatePayload.requires_notary = data.requires_notary;
        
        
        if (data.service_warning !== undefined) updatePayload.service_warning = data.service_warning;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.tenant !== undefined) {
            await contract_folders.setTenant(
              
              data.tenant,
              
              { transaction }
            );
        }
        
        if (data.created_by_user !== undefined) {
            await contract_folders.setCreated_by_user(
              
              data.created_by_user,
              
              { transaction }
            );
        }
        
        if (data.service_type !== undefined) {
            await contract_folders.setService_type(
              
              data.service_type,
              
              { transaction }
            );
        }
        
        if (data.workflow_definition !== undefined) {
            await contract_folders.setWorkflow_definition(
              
              data.workflow_definition,
              
              { transaction }
            );
        }
        
        if (data.document_template !== undefined) {
            await contract_folders.setDocument_template(
              
              data.document_template,
              
              { transaction }
            );
        }
        
        if (data.location !== undefined) {
            await contract_folders.setLocation(
              
              data.location,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await contract_folders.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return contract_folders;
    }

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

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

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


        return contract_folders;
    }

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

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

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

        await contract_folders.destroy({
            transaction
        });

        return contract_folders;
    }

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

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

        if (!contract_folders) {
            return contract_folders;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.contract_documents_contract_folder = await contract_folders.getContract_documents_contract_folder({
            transaction
        });
        
        
        
        output.contract_participants_contract_folder = await contract_folders.getContract_participants_contract_folder({
            transaction
        });
        
        
        
        output.payments_contract_folder = await contract_folders.getPayments_contract_folder({
            transaction
        });
        
        
        
        
        
        
        
        output.notification_records_contract_folder = await contract_folders.getNotification_records_contract_folder({
            transaction
        });
        
        
        
        output.signing_actions_contract_folder = await contract_folders.getSigning_actions_contract_folder({
            transaction
        });
        
        
        
        
        
        output.support_tickets_contract_folder = await contract_folders.getSupport_tickets_contract_folder({
            transaction
        });
        
        
        
        
        
        
        output.audit_events_contract_folder = await contract_folders.getAudit_events_contract_folder({
            transaction
        });
        
        
        
        output.tenant = await contract_folders.getTenant({
            transaction
        });
        
        
        output.created_by_user = await contract_folders.getCreated_by_user({
            transaction
        });
        
        
        output.service_type = await contract_folders.getService_type({
            transaction
        });
        
        
        output.workflow_definition = await contract_folders.getWorkflow_definition({
            transaction
        });
        
        
        output.document_template = await contract_folders.getDocument_template({
            transaction
        });
        
        
        output.location = await contract_folders.getLocation({
            transaction
        });
        
        
        output.organizations = await contract_folders.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.tenants,
        as: 'tenant',
        
        where: filter.tenant ? {
          [Op.or]: [
            { id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
            {
              trade_name: {
                [Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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

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

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

      {
        model: db.locations,
        as: 'location',
        
        where: filter.location ? {
          [Op.or]: [
            { id: { [Op.in]: filter.location.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.location.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.title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'contract_folders',
                        'title',
                        filter.title,
                    ),
                };
            }
            
            if (filter.service_warning) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'contract_folders',
                        'service_warning',
                        filter.service_warning,
                    ),
                };
            }
            

            
            

            
            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.deadline_atRange) {
                const [start, end] = filter.deadline_atRange;

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

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

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

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


      

      

      

      

      

      

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

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

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

    
};

