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

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

        const footer_settings = await db.footer_settings.create(
            {
                id: data.id || undefined,
        
        store_description: data.store_description
        ||
        null
            ,
            
        copyright_text: data.copyright_text
        ||
        null
            ,
            
        footer_banner_enabled: data.footer_banner_enabled
        ||
        false
        
            ,
            
        footer_banner_text: data.footer_banner_text
        ||
        null
            ,
            
        footer_banner_url: data.footer_banner_url
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        
        await footer_settings.setSocial_links(data.social_links || [], {
            transaction,
        });
        
        await footer_settings.setFooter_links(data.footer_links || [], {
            transaction,
        });
        
        await footer_settings.setPayment_icons(data.payment_icons || [], {
            transaction,
        });
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.footer_settings.getTableName(),
                belongsToColumn: 'store_logo',
                belongsToId: footer_settings.id,
            },
            data.store_logo,
            options,
        );
        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.footer_settings.getTableName(),
                belongsToColumn: 'footer_banner_image',
                belongsToId: footer_settings.id,
            },
            data.footer_banner_image,
            options,
        );
        

        return footer_settings;
    }
    

    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 footer_settingsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                store_description: item.store_description
            ||
            null
            ,
            
                copyright_text: item.copyright_text
            ||
            null
            ,
            
                footer_banner_enabled: item.footer_banner_enabled
            ||
            false
        
            ,
            
                footer_banner_text: item.footer_banner_text
            ||
            null
            ,
            
                footer_banner_url: item.footer_banner_url
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        
        for (let i = 0; i < footer_settings.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.footer_settings.getTableName(),
                    belongsToColumn: 'store_logo',
                    belongsToId: footer_settings[i].id,
                },
                data[i].store_logo,
                options,
            );
        }
        
        for (let i = 0; i < footer_settings.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.footer_settings.getTableName(),
                    belongsToColumn: 'footer_banner_image',
                    belongsToId: footer_settings[i].id,
                },
                data[i].footer_banner_image,
                options,
            );
        }
        

        return footer_settings;
    }

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

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


        

        const updatePayload = {};
        
        if (data.store_description !== undefined) updatePayload.store_description = data.store_description;
        
        
        if (data.copyright_text !== undefined) updatePayload.copyright_text = data.copyright_text;
        
        
        if (data.footer_banner_enabled !== undefined) updatePayload.footer_banner_enabled = data.footer_banner_enabled;
        
        
        if (data.footer_banner_text !== undefined) updatePayload.footer_banner_text = data.footer_banner_text;
        
        
        if (data.footer_banner_url !== undefined) updatePayload.footer_banner_url = data.footer_banner_url;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        
        if (data.social_links !== undefined) {
            await footer_settings.setSocial_links(data.social_links, { transaction });
        }
        
        if (data.footer_links !== undefined) {
            await footer_settings.setFooter_links(data.footer_links, { transaction });
        }
        
        if (data.payment_icons !== undefined) {
            await footer_settings.setPayment_icons(data.payment_icons, { transaction });
        }
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.footer_settings.getTableName(),
                belongsToColumn: 'store_logo',
                belongsToId: footer_settings.id,
            },
            data.store_logo,
            options,
        );
        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.footer_settings.getTableName(),
                belongsToColumn: 'footer_banner_image',
                belongsToId: footer_settings.id,
            },
            data.footer_banner_image,
            options,
        );
        

        return footer_settings;
    }

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

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

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


        return footer_settings;
    }

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

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

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

        await footer_settings.destroy({
            transaction
        });

        return footer_settings;
    }

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

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

        if (!footer_settings) {
            return footer_settings;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.social_links_footer = await footer_settings.getSocial_links_footer({
            transaction
        });
        
        
        output.footer_links_footer = await footer_settings.getFooter_links_footer({
            transaction
        });
        
        
        
        output.payment_icons_footer = await footer_settings.getPayment_icons_footer({
            transaction
        });
        
        
        
        
        
        output.store_logo = await footer_settings.getStore_logo({
            transaction
        });
        
        
        output.footer_banner_image = await footer_settings.getFooter_banner_image({
            transaction
        });
        
        
        output.social_links = await footer_settings.getSocial_links({
            transaction
        });
        
        
        output.footer_links = await footer_settings.getFooter_links({
            transaction
        });
        
        
        output.payment_icons = await footer_settings.getPayment_icons({
            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.social_links,
        as: 'social_links',
        required: false,
      },

      {
        model: db.footer_links,
        as: 'footer_links',
        required: false,
      },

      {
        model: db.payment_icons,
        as: 'payment_icons',
        required: false,
      },


      {
        model: db.file,
        as: 'store_logo',
      },

      {
        model: db.file,
        as: 'footer_banner_image',
      },

    ];

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

            
            if (filter.store_description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'footer_settings',
                        'store_description',
                        filter.store_description,
                    ),
                };
            }
            
            if (filter.copyright_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'footer_settings',
                        'copyright_text',
                        filter.copyright_text,
                    ),
                };
            }
            
            if (filter.footer_banner_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'footer_settings',
                        'footer_banner_text',
                        filter.footer_banner_text,
                    ),
                };
            }
            
            if (filter.footer_banner_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'footer_settings',
                        'footer_banner_url',
                        filter.footer_banner_url,
                    ),
                };
            }
            

            
            

            

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

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



      if (filter.social_links) {
        const searchTerms = filter.social_links.split('|');

        include = [
          {
            model: db.social_links,
            as: 'social_links_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  url: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }

      if (filter.footer_links) {
        const searchTerms = filter.footer_links.split('|');

        include = [
          {
            model: db.footer_links,
            as: 'footer_links_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  label: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }

      if (filter.payment_icons) {
        const searchTerms = filter.payment_icons.split('|');

        include = [
          {
            model: db.payment_icons,
            as: 'payment_icons_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  method: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }


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

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

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

    
};

