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

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

        const template_fields = await db.template_fields.create(
            {
                id: data.id || undefined,
        
        field_key: data.field_key
        ||
        null
            ,
            
        label: data.label
        ||
        null
            ,
            
        value_type: data.value_type
        ||
        null
            ,
            
        is_required: data.is_required
        ||
        false
        
            ,
            
        default_value: data.default_value
        ||
        null
            ,
            
        sort_order: data.sort_order
        ||
        null
            ,
            
        help_text: data.help_text
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await template_fields.setTemplate( data.template || null, {
            transaction,
        });
        

        

        

        return template_fields;
    }
    

    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 template_fieldsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                field_key: item.field_key
            ||
            null
            ,
            
                label: item.label
            ||
            null
            ,
            
                value_type: item.value_type
            ||
            null
            ,
            
                is_required: item.is_required
            ||
            false
        
            ,
            
                default_value: item.default_value
            ||
            null
            ,
            
                sort_order: item.sort_order
            ||
            null
            ,
            
                help_text: item.help_text
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return template_fields;
    }

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

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


        

        const updatePayload = {};
        
        if (data.field_key !== undefined) updatePayload.field_key = data.field_key;
        
        
        if (data.label !== undefined) updatePayload.label = data.label;
        
        
        if (data.value_type !== undefined) updatePayload.value_type = data.value_type;
        
        
        if (data.is_required !== undefined) updatePayload.is_required = data.is_required;
        
        
        if (data.default_value !== undefined) updatePayload.default_value = data.default_value;
        
        
        if (data.sort_order !== undefined) updatePayload.sort_order = data.sort_order;
        
        
        if (data.help_text !== undefined) updatePayload.help_text = data.help_text;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.template !== undefined) {
            await template_fields.setTemplate(
              
              data.template,
              
              { transaction }
            );
        }
        

        
        

        

        return template_fields;
    }

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

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

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


        return template_fields;
    }

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

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

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

        await template_fields.destroy({
            transaction
        });

        return template_fields;
    }

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

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

        if (!template_fields) {
            return template_fields;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.template = await template_fields.getTemplate({
            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.legal_templates,
        as: 'template',
        
        where: filter.template ? {
          [Op.or]: [
            { id: { [Op.in]: filter.template.split('|').map(term => Utils.uuid(term)) } },
            {
              template_name: {
                [Op.or]: filter.template.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.field_key) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'template_fields',
                        'field_key',
                        filter.field_key,
                    ),
                };
            }
            
            if (filter.label) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'template_fields',
                        'label',
                        filter.label,
                    ),
                };
            }
            
            if (filter.default_value) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'template_fields',
                        'default_value',
                        filter.default_value,
                    ),
                };
            }
            
            if (filter.help_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'template_fields',
                        'help_text',
                        filter.help_text,
                    ),
                };
            }
            

            
            

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

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

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

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

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


      



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

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

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

    
};

