
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,
        
        brand_name: data.brand_name
        ||
        null
            ,
            
        footer_tagline: data.footer_tagline
        ||
        null
            ,
            
        primary_color_hex: data.primary_color_hex
        ||
        null
            ,
            
        secondary_color_hex: data.secondary_color_hex
        ||
        null
            ,
            
        accent_color_hex: data.accent_color_hex
        ||
        null
            ,
            
        default_meta_title: data.default_meta_title
        ||
        null
            ,
            
        default_meta_description: data.default_meta_description
        ||
        null
            ,
            
        default_meta_keywords: data.default_meta_keywords
        ||
        null
            ,
            
        maintenance_mode: data.maintenance_mode
        ||
        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,
        );
        

        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,
                
                brand_name: item.brand_name
            ||
            null
            ,
            
                footer_tagline: item.footer_tagline
            ||
            null
            ,
            
                primary_color_hex: item.primary_color_hex
            ||
            null
            ,
            
                secondary_color_hex: item.secondary_color_hex
            ||
            null
            ,
            
                accent_color_hex: item.accent_color_hex
            ||
            null
            ,
            
                default_meta_title: item.default_meta_title
            ||
            null
            ,
            
                default_meta_description: item.default_meta_description
            ||
            null
            ,
            
                default_meta_keywords: item.default_meta_keywords
            ||
            null
            ,
            
                maintenance_mode: item.maintenance_mode
            ||
            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,
            );
        }
        

        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.brand_name !== undefined) updatePayload.brand_name = data.brand_name;
        
        
        if (data.footer_tagline !== undefined) updatePayload.footer_tagline = data.footer_tagline;
        
        
        if (data.primary_color_hex !== undefined) updatePayload.primary_color_hex = data.primary_color_hex;
        
        
        if (data.secondary_color_hex !== undefined) updatePayload.secondary_color_hex = data.secondary_color_hex;
        
        
        if (data.accent_color_hex !== undefined) updatePayload.accent_color_hex = data.accent_color_hex;
        
        
        if (data.default_meta_title !== undefined) updatePayload.default_meta_title = data.default_meta_title;
        
        
        if (data.default_meta_description !== undefined) updatePayload.default_meta_description = data.default_meta_description;
        
        
        if (data.default_meta_keywords !== undefined) updatePayload.default_meta_keywords = data.default_meta_keywords;
        
        
        if (data.maintenance_mode !== undefined) updatePayload.maintenance_mode = data.maintenance_mode;
        
        
        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,
        );
        

        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
        });
        
        

        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',
      },

    ];

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

            
            if (filter.brand_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'site_settings',
                        'brand_name',
                        filter.brand_name,
                    ),
                };
            }
            
            if (filter.footer_tagline) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'site_settings',
                        'footer_tagline',
                        filter.footer_tagline,
                    ),
                };
            }
            
            if (filter.primary_color_hex) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'site_settings',
                        'primary_color_hex',
                        filter.primary_color_hex,
                    ),
                };
            }
            
            if (filter.secondary_color_hex) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'site_settings',
                        'secondary_color_hex',
                        filter.secondary_color_hex,
                    ),
                };
            }
            
            if (filter.accent_color_hex) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'site_settings',
                        'accent_color_hex',
                        filter.accent_color_hex,
                    ),
                };
            }
            
            if (filter.default_meta_title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'site_settings',
                        'default_meta_title',
                        filter.default_meta_title,
                    ),
                };
            }
            
            if (filter.default_meta_description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'site_settings',
                        'default_meta_description',
                        filter.default_meta_description,
                    ),
                };
            }
            
            if (filter.default_meta_keywords) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'site_settings',
                        'default_meta_keywords',
                        filter.default_meta_keywords,
                    ),
                };
            }
            

            
            

            

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

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




            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',
                        'brand_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

