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

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

        const hero_slides = await db.hero_slides.create(
            {
                id: data.id || undefined,
        
        headline_ar: data.headline_ar
        ||
        null
            ,
            
        subheadline_ar: data.subheadline_ar
        ||
        null
            ,
            
        cta_type: data.cta_type
        ||
        null
            ,
            
        cta_label_ar: data.cta_label_ar
        ||
        null
            ,
            
        cta_url: data.cta_url
        ||
        null
            ,
            
        sort_order: data.sort_order
        ||
        null
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

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

        return hero_slides;
    }
    

    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 hero_slidesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                headline_ar: item.headline_ar
            ||
            null
            ,
            
                subheadline_ar: item.subheadline_ar
            ||
            null
            ,
            
                cta_type: item.cta_type
            ||
            null
            ,
            
                cta_label_ar: item.cta_label_ar
            ||
            null
            ,
            
                cta_url: item.cta_url
            ||
            null
            ,
            
                sort_order: item.sort_order
            ||
            null
            ,
            
                is_active: item.is_active
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return hero_slides;
    }

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

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


        

        const updatePayload = {};
        
        if (data.headline_ar !== undefined) updatePayload.headline_ar = data.headline_ar;
        
        
        if (data.subheadline_ar !== undefined) updatePayload.subheadline_ar = data.subheadline_ar;
        
        
        if (data.cta_type !== undefined) updatePayload.cta_type = data.cta_type;
        
        
        if (data.cta_label_ar !== undefined) updatePayload.cta_label_ar = data.cta_label_ar;
        
        
        if (data.cta_url !== undefined) updatePayload.cta_url = data.cta_url;
        
        
        if (data.sort_order !== undefined) updatePayload.sort_order = data.sort_order;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        

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

        return hero_slides;
    }

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

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

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


        return hero_slides;
    }

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

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

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

        await hero_slides.destroy({
            transaction
        });

        return hero_slides;
    }

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

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

        if (!hero_slides) {
            return hero_slides;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.background_images = await hero_slides.getBackground_images({
            transaction
        });
        
        
        output.background_videos = await hero_slides.getBackground_videos({
            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.file,
        as: 'background_images',
      },

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

    ];

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

            
            if (filter.headline_ar) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'hero_slides',
                        'headline_ar',
                        filter.headline_ar,
                    ),
                };
            }
            
            if (filter.subheadline_ar) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'hero_slides',
                        'subheadline_ar',
                        filter.subheadline_ar,
                    ),
                };
            }
            
            if (filter.cta_label_ar) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'hero_slides',
                        'cta_label_ar',
                        filter.cta_label_ar,
                    ),
                };
            }
            
            if (filter.cta_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'hero_slides',
                        'cta_url',
                        filter.cta_url,
                    ),
                };
            }
            

            
            

            
            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.cta_type) {
                where = {
                    ...where,
                cta_type: filter.cta_type,
            };
            }
            
            if (filter.is_active) {
                where = {
                    ...where,
                is_active: filter.is_active,
            };
            }
            




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

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

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

    
};

