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

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

        const translations = await db.translations.create(
            {
                id: data.id || undefined,
        
        value_text: data.value_text
        ||
        null
            ,
            
        published_at: data.published_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await translations.setTranslation_key( data.translation_key || null, {
            transaction,
        });
        
        await translations.setLanguage( data.language || null, {
            transaction,
        });
        
        await translations.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return translations;
    }
    

    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 translationsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                value_text: item.value_text
            ||
            null
            ,
            
                published_at: item.published_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return translations;
    }

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


        

        const updatePayload = {};
        
        if (data.value_text !== undefined) updatePayload.value_text = data.value_text;
        
        
        if (data.published_at !== undefined) updatePayload.published_at = data.published_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.translation_key !== undefined) {
            await translations.setTranslation_key(
              
              data.translation_key,
              
              { transaction }
            );
        }
        
        if (data.language !== undefined) {
            await translations.setLanguage(
              
              data.language,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await translations.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return translations;
    }

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

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

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


        return translations;
    }

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

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

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

        await translations.destroy({
            transaction
        });

        return translations;
    }

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

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

        if (!translations) {
            return translations;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.translation_key = await translations.getTranslation_key({
            transaction
        });
        
        
        output.language = await translations.getLanguage({
            transaction
        });
        
        
        output.organizations = await translations.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.translation_keys,
        as: 'translation_key',
        
        where: filter.translation_key ? {
          [Op.or]: [
            { id: { [Op.in]: filter.translation_key.split('|').map(term => Utils.uuid(term)) } },
            {
              key_name: {
                [Op.or]: filter.translation_key.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.languages,
        as: 'language',
        
        where: filter.language ? {
          [Op.or]: [
            { id: { [Op.in]: filter.language.split('|').map(term => Utils.uuid(term)) } },
            {
              language_name: {
                [Op.or]: filter.language.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.value_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'translations',
                        'value_text',
                        filter.value_text,
                    ),
                };
            }
            

            
            

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

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

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

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

            


      

      

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

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

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

    
};

