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

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

        const email_templates = await db.email_templates.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        template_key: data.template_key
        ||
        null
            ,
            
        subject_fr: data.subject_fr
        ||
        null
            ,
            
        subject_en: data.subject_en
        ||
        null
            ,
            
        body_fr: data.body_fr
        ||
        null
            ,
            
        body_en: data.body_en
        ||
        null
            ,
            
        active: data.active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await email_templates.setTenant( data.tenant || null, {
            transaction,
        });
        
        await email_templates.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return email_templates;
    }
    

    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 email_templatesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                template_key: item.template_key
            ||
            null
            ,
            
                subject_fr: item.subject_fr
            ||
            null
            ,
            
                subject_en: item.subject_en
            ||
            null
            ,
            
                body_fr: item.body_fr
            ||
            null
            ,
            
                body_en: item.body_en
            ||
            null
            ,
            
                active: item.active
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return email_templates;
    }

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.template_key !== undefined) updatePayload.template_key = data.template_key;
        
        
        if (data.subject_fr !== undefined) updatePayload.subject_fr = data.subject_fr;
        
        
        if (data.subject_en !== undefined) updatePayload.subject_en = data.subject_en;
        
        
        if (data.body_fr !== undefined) updatePayload.body_fr = data.body_fr;
        
        
        if (data.body_en !== undefined) updatePayload.body_en = data.body_en;
        
        
        if (data.active !== undefined) updatePayload.active = data.active;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.tenant !== undefined) {
            await email_templates.setTenant(
              
              data.tenant,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await email_templates.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return email_templates;
    }

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

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

        if (email_templates.length !== ids.length) {
            const error = new Error('One or more items were not found in the current organization scope.');
            error.code = 404;
            throw error;
        }

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


        return email_templates;
    }

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

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

        if (!email_templates) {
            const error = new Error('Item not found in the current organization scope.');
            error.code = 404;
            throw error;
        }

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

        await email_templates.destroy({
            transaction
        });

        return email_templates;
    }

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

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

        if (!email_templates) {
            return email_templates;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.tenant = await email_templates.getTenant({
            transaction
        });
        
        
        output.organizations = await email_templates.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)) } },
            {
              name: {
                [Op.or]: filter.tenant.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.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'email_templates',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.subject_fr) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'email_templates',
                        'subject_fr',
                        filter.subject_fr,
                    ),
                };
            }
            
            if (filter.subject_en) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'email_templates',
                        'subject_en',
                        filter.subject_en,
                    ),
                };
            }
            
            if (filter.body_fr) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'email_templates',
                        'body_fr',
                        filter.body_fr,
                    ),
                };
            }
            
            if (filter.body_en) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'email_templates',
                        'body_en',
                        filter.body_en,
                    ),
                };
            }
            

            
            

            

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

            
            if (filter.template_key) {
                where = {
                    ...where,
                template_key: filter.template_key,
            };
            }
            
            if (filter.active) {
                where = {
                    ...where,
                active: filter.active,
            };
            }
            


      

      
      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.email_templates.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.organizationsId = organizationId;
        }
        

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

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

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

    
};

