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

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

        const footer_content_blocks = await db.footer_content_blocks.create(
            {
                id: data.id || undefined,
        
        store_description_ar: data.store_description_ar
        ||
        null
            ,
            
        store_description_en: data.store_description_en
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        
        await footer_content_blocks.setSocial_links(data.social_links || [], {
            transaction,
        });
        
        await footer_content_blocks.setFooter_links(data.footer_links || [], {
            transaction,
        });
        
        await footer_content_blocks.setPayment_badges(data.payment_badges || [], {
            transaction,
        });
        

        

        return footer_content_blocks;
    }
    

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

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

        // For each item created, replace relation files
        

        return footer_content_blocks;
    }

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

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


        

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

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

        
        

        
        
        if (data.social_links !== undefined) {
            await footer_content_blocks.setSocial_links(data.social_links, { transaction });
        }
        
        if (data.footer_links !== undefined) {
            await footer_content_blocks.setFooter_links(data.footer_links, { transaction });
        }
        
        if (data.payment_badges !== undefined) {
            await footer_content_blocks.setPayment_badges(data.payment_badges, { transaction });
        }
        

        

        return footer_content_blocks;
    }

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

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

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


        return footer_content_blocks;
    }

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

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

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

        await footer_content_blocks.destroy({
            transaction
        });

        return footer_content_blocks;
    }

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

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

        if (!footer_content_blocks) {
            return footer_content_blocks;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.social_links_footer_content_block = await footer_content_blocks.getSocial_links_footer_content_block({
            transaction
        });
        
        
        output.footer_links_footer_content_block = await footer_content_blocks.getFooter_links_footer_content_block({
            transaction
        });
        
        
        output.payment_badges_footer_content_block = await footer_content_blocks.getPayment_badges_footer_content_block({
            transaction
        });
        
        
        
        
        
        
        
        
        output.social_links = await footer_content_blocks.getSocial_links({
            transaction
        });
        
        
        output.footer_links = await footer_content_blocks.getFooter_links({
            transaction
        });
        
        
        output.payment_badges = await footer_content_blocks.getPayment_badges({
            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_badges,
        as: 'payment_badges',
        required: false,
      },


    ];

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

            
            if (filter.store_description_ar) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'footer_content_blocks',
                        'store_description_ar',
                        filter.store_description_ar,
                    ),
                };
            }
            
            if (filter.store_description_en) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'footer_content_blocks',
                        'store_description_en',
                        filter.store_description_en,
                    ),
                };
            }
            

            
            

            

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

            



      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_ar: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }

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

        include = [
          {
            model: db.payment_badges,
            as: 'payment_badges_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.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_content_blocks.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_content_blocks',
                        'store_description_ar',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

