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

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

        const document_retention_policies = await db.document_retention_policies.create(
            {
                id: data.id || undefined,
        
        type: data.type
        ||
        null
            ,
            
        keep_min_versions: data.keep_min_versions
        ||
        null
            ,
            
        keep_files_days: data.keep_files_days
        ||
        null
            ,
            
        keep_version_days: data.keep_version_days
        ||
        null
            ,
            
        keep_audit_after_file_removal: data.keep_audit_after_file_removal
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await document_retention_policies.setCompany( data.company || null, {
            transaction,
        });
        

        

        

        return document_retention_policies;
    }
    

    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 document_retention_policiesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                type: item.type
            ||
            null
            ,
            
                keep_min_versions: item.keep_min_versions
            ||
            null
            ,
            
                keep_files_days: item.keep_files_days
            ||
            null
            ,
            
                keep_version_days: item.keep_version_days
            ||
            null
            ,
            
                keep_audit_after_file_removal: item.keep_audit_after_file_removal
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return document_retention_policies;
    }

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

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


        

        const updatePayload = {};
        
        if (data.type !== undefined) updatePayload.type = data.type;
        
        
        if (data.keep_min_versions !== undefined) updatePayload.keep_min_versions = data.keep_min_versions;
        
        
        if (data.keep_files_days !== undefined) updatePayload.keep_files_days = data.keep_files_days;
        
        
        if (data.keep_version_days !== undefined) updatePayload.keep_version_days = data.keep_version_days;
        
        
        if (data.keep_audit_after_file_removal !== undefined) updatePayload.keep_audit_after_file_removal = data.keep_audit_after_file_removal;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.company !== undefined) {
            await document_retention_policies.setCompany(
              
              data.company,
              
              { transaction }
            );
        }
        

        
        

        

        return document_retention_policies;
    }

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

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

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


        return document_retention_policies;
    }

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

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

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

        await document_retention_policies.destroy({
            transaction
        });

        return document_retention_policies;
    }

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

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

        if (!document_retention_policies) {
            return document_retention_policies;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.company = await document_retention_policies.getCompany({
            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.companies,
        as: 'company',
        
        where: filter.company ? {
          [Op.or]: [
            { id: { [Op.in]: filter.company.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.company.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            

            
            

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

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

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

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

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

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

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

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

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


      



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

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

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

    
};

