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

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

        const home_section_items = await db.home_section_items.create(
            {
                id: data.id || undefined,
        
        item_type: data.item_type
        ||
        null
            ,
            
        link_url: data.link_url
        ||
        null
            ,
            
        item_title: data.item_title
        ||
        null
            ,
            
        sort_order: data.sort_order
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await home_section_items.setHome_section( data.home_section || null, {
            transaction,
        });
        
        await home_section_items.setProduct( data.product || null, {
            transaction,
        });
        
        await home_section_items.setCategory( data.category || null, {
            transaction,
        });
        

        

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

        return home_section_items;
    }
    

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

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

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

        return home_section_items;
    }

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

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


        

        const updatePayload = {};
        
        if (data.item_type !== undefined) updatePayload.item_type = data.item_type;
        
        
        if (data.link_url !== undefined) updatePayload.link_url = data.link_url;
        
        
        if (data.item_title !== undefined) updatePayload.item_title = data.item_title;
        
        
        if (data.sort_order !== undefined) updatePayload.sort_order = data.sort_order;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.home_section !== undefined) {
            await home_section_items.setHome_section(
              
              data.home_section,
              
              { transaction }
            );
        }
        
        if (data.product !== undefined) {
            await home_section_items.setProduct(
              
              data.product,
              
              { transaction }
            );
        }
        
        if (data.category !== undefined) {
            await home_section_items.setCategory(
              
              data.category,
              
              { transaction }
            );
        }
        

        
        

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

        return home_section_items;
    }

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

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

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


        return home_section_items;
    }

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

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

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

        await home_section_items.destroy({
            transaction
        });

        return home_section_items;
    }

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

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

        if (!home_section_items) {
            return home_section_items;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.home_section = await home_section_items.getHome_section({
            transaction
        });
        
        
        output.product = await home_section_items.getProduct({
            transaction
        });
        
        
        output.category = await home_section_items.getCategory({
            transaction
        });
        
        
        output.item_images = await home_section_items.getItem_images({
            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.home_sections,
        as: 'home_section',
        
        where: filter.home_section ? {
          [Op.or]: [
            { id: { [Op.in]: filter.home_section.split('|').map(term => Utils.uuid(term)) } },
            {
              section_title: {
                [Op.or]: filter.home_section.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.products,
        as: 'product',
        
        where: filter.product ? {
          [Op.or]: [
            { id: { [Op.in]: filter.product.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.product.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.categories,
        as: 'category',
        
        where: filter.category ? {
          [Op.or]: [
            { id: { [Op.in]: filter.category.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.category.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



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

    ];

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

            
            if (filter.link_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'home_section_items',
                        'link_url',
                        filter.link_url,
                    ),
                };
            }
            
            if (filter.item_title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'home_section_items',
                        'item_title',
                        filter.item_title,
                    ),
                };
            }
            

            
            

            
            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.item_type) {
                where = {
                    ...where,
                item_type: filter.item_type,
            };
            }
            


      

      

      



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

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

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

    
};

