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

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

        const site_settings = await db.site_settings.create(
            {
                id: data.id || undefined,
        
        site_name: data.site_name
        ||
        null
            ,
            
        tagline: data.tagline
        ||
        null
            ,
            
        primary_phone: data.primary_phone
        ||
        null
            ,
            
        secondary_phone: data.secondary_phone
        ||
        null
            ,
            
        whatsapp_number: data.whatsapp_number
        ||
        null
            ,
            
        contact_email: data.contact_email
        ||
        null
            ,
            
        address: data.address
        ||
        null
            ,
            
        google_maps_embed: data.google_maps_embed
        ||
        null
            ,
            
        working_hours: data.working_hours
        ||
        null
            ,
            
        facebook_url: data.facebook_url
        ||
        null
            ,
            
        instagram_url: data.instagram_url
        ||
        null
            ,
            
        linkedin_url: data.linkedin_url
        ||
        null
            ,
            
        youtube_url: data.youtube_url
        ||
        null
            ,
            
        show_cookie_banner: data.show_cookie_banner
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

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

        return site_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 site_settingsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                site_name: item.site_name
            ||
            null
            ,
            
                tagline: item.tagline
            ||
            null
            ,
            
                primary_phone: item.primary_phone
            ||
            null
            ,
            
                secondary_phone: item.secondary_phone
            ||
            null
            ,
            
                whatsapp_number: item.whatsapp_number
            ||
            null
            ,
            
                contact_email: item.contact_email
            ||
            null
            ,
            
                address: item.address
            ||
            null
            ,
            
                google_maps_embed: item.google_maps_embed
            ||
            null
            ,
            
                working_hours: item.working_hours
            ||
            null
            ,
            
                facebook_url: item.facebook_url
            ||
            null
            ,
            
                instagram_url: item.instagram_url
            ||
            null
            ,
            
                linkedin_url: item.linkedin_url
            ||
            null
            ,
            
                youtube_url: item.youtube_url
            ||
            null
            ,
            
                show_cookie_banner: item.show_cookie_banner
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return site_settings;
    }

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

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


        

        const updatePayload = {};
        
        if (data.site_name !== undefined) updatePayload.site_name = data.site_name;
        
        
        if (data.tagline !== undefined) updatePayload.tagline = data.tagline;
        
        
        if (data.primary_phone !== undefined) updatePayload.primary_phone = data.primary_phone;
        
        
        if (data.secondary_phone !== undefined) updatePayload.secondary_phone = data.secondary_phone;
        
        
        if (data.whatsapp_number !== undefined) updatePayload.whatsapp_number = data.whatsapp_number;
        
        
        if (data.contact_email !== undefined) updatePayload.contact_email = data.contact_email;
        
        
        if (data.address !== undefined) updatePayload.address = data.address;
        
        
        if (data.google_maps_embed !== undefined) updatePayload.google_maps_embed = data.google_maps_embed;
        
        
        if (data.working_hours !== undefined) updatePayload.working_hours = data.working_hours;
        
        
        if (data.facebook_url !== undefined) updatePayload.facebook_url = data.facebook_url;
        
        
        if (data.instagram_url !== undefined) updatePayload.instagram_url = data.instagram_url;
        
        
        if (data.linkedin_url !== undefined) updatePayload.linkedin_url = data.linkedin_url;
        
        
        if (data.youtube_url !== undefined) updatePayload.youtube_url = data.youtube_url;
        
        
        if (data.show_cookie_banner !== undefined) updatePayload.show_cookie_banner = data.show_cookie_banner;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        

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

        return site_settings;
    }

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

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

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


        return site_settings;
    }

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

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

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

        await site_settings.destroy({
            transaction
        });

        return site_settings;
    }

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

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

        if (!site_settings) {
            return site_settings;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.logo_images = await site_settings.getLogo_images({
            transaction
        });
        
        
        output.favicon_images = await site_settings.getFavicon_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.file,
        as: 'logo_images',
      },

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

    ];

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

            
            if (filter.site_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'site_settings',
                        'site_name',
                        filter.site_name,
                    ),
                };
            }
            
            if (filter.tagline) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'site_settings',
                        'tagline',
                        filter.tagline,
                    ),
                };
            }
            
            if (filter.primary_phone) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'site_settings',
                        'primary_phone',
                        filter.primary_phone,
                    ),
                };
            }
            
            if (filter.secondary_phone) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'site_settings',
                        'secondary_phone',
                        filter.secondary_phone,
                    ),
                };
            }
            
            if (filter.whatsapp_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'site_settings',
                        'whatsapp_number',
                        filter.whatsapp_number,
                    ),
                };
            }
            
            if (filter.contact_email) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'site_settings',
                        'contact_email',
                        filter.contact_email,
                    ),
                };
            }
            
            if (filter.address) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'site_settings',
                        'address',
                        filter.address,
                    ),
                };
            }
            
            if (filter.google_maps_embed) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'site_settings',
                        'google_maps_embed',
                        filter.google_maps_embed,
                    ),
                };
            }
            
            if (filter.working_hours) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'site_settings',
                        'working_hours',
                        filter.working_hours,
                    ),
                };
            }
            
            if (filter.facebook_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'site_settings',
                        'facebook_url',
                        filter.facebook_url,
                    ),
                };
            }
            
            if (filter.instagram_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'site_settings',
                        'instagram_url',
                        filter.instagram_url,
                    ),
                };
            }
            
            if (filter.linkedin_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'site_settings',
                        'linkedin_url',
                        filter.linkedin_url,
                    ),
                };
            }
            
            if (filter.youtube_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'site_settings',
                        'youtube_url',
                        filter.youtube_url,
                    ),
                };
            }
            

            
            

            

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

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




            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.site_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(
                        'site_settings',
                        'site_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

