
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_ar: data.site_name_ar
        ||
        null
            ,
            
        site_tagline_ar: data.site_tagline_ar
        ||
        null
            ,
            
        primary_font: data.primary_font
        ||
        null
            ,
            
        direction: data.direction
        ||
        null
            ,
            
        primary_color_hex: data.primary_color_hex
        ||
        null
            ,
            
        accent_color_hex: data.accent_color_hex
        ||
        null
            ,
            
        seo_default_title_ar: data.seo_default_title_ar
        ||
        null
            ,
            
        seo_default_description_ar: data.seo_default_description_ar
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.site_settings.getTableName(),
                belongsToColumn: 'logo',
                belongsToId: site_settings.id,
            },
            data.logo,
            options,
        );
        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.site_settings.getTableName(),
                belongsToColumn: 'favicon',
                belongsToId: site_settings.id,
            },
            data.favicon,
            options,
        );
        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.site_settings.getTableName(),
                belongsToColumn: 'brand_guidelines',
                belongsToId: site_settings.id,
            },
            data.brand_guidelines,
            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_ar: item.site_name_ar
            ||
            null
            ,
            
                site_tagline_ar: item.site_tagline_ar
            ||
            null
            ,
            
                primary_font: item.primary_font
            ||
            null
            ,
            
                direction: item.direction
            ||
            null
            ,
            
                primary_color_hex: item.primary_color_hex
            ||
            null
            ,
            
                accent_color_hex: item.accent_color_hex
            ||
            null
            ,
            
                seo_default_title_ar: item.seo_default_title_ar
            ||
            null
            ,
            
                seo_default_description_ar: item.seo_default_description_ar
            ||
            null
            ,
            
            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',
                    belongsToId: site_settings[i].id,
                },
                data[i].logo,
                options,
            );
        }
        
        for (let i = 0; i < site_settings.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.site_settings.getTableName(),
                    belongsToColumn: 'favicon',
                    belongsToId: site_settings[i].id,
                },
                data[i].favicon,
                options,
            );
        }
        
        for (let i = 0; i < site_settings.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.site_settings.getTableName(),
                    belongsToColumn: 'brand_guidelines',
                    belongsToId: site_settings[i].id,
                },
                data[i].brand_guidelines,
                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_ar !== undefined) updatePayload.site_name_ar = data.site_name_ar;
        
        
        if (data.site_tagline_ar !== undefined) updatePayload.site_tagline_ar = data.site_tagline_ar;
        
        
        if (data.primary_font !== undefined) updatePayload.primary_font = data.primary_font;
        
        
        if (data.direction !== undefined) updatePayload.direction = data.direction;
        
        
        if (data.primary_color_hex !== undefined) updatePayload.primary_color_hex = data.primary_color_hex;
        
        
        if (data.accent_color_hex !== undefined) updatePayload.accent_color_hex = data.accent_color_hex;
        
        
        if (data.seo_default_title_ar !== undefined) updatePayload.seo_default_title_ar = data.seo_default_title_ar;
        
        
        if (data.seo_default_description_ar !== undefined) updatePayload.seo_default_description_ar = data.seo_default_description_ar;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.site_settings.getTableName(),
                belongsToColumn: 'logo',
                belongsToId: site_settings.id,
            },
            data.logo,
            options,
        );
        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.site_settings.getTableName(),
                belongsToColumn: 'favicon',
                belongsToId: site_settings.id,
            },
            data.favicon,
            options,
        );
        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.site_settings.getTableName(),
                belongsToColumn: 'brand_guidelines',
                belongsToId: site_settings.id,
            },
            data.brand_guidelines,
            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 = await site_settings.getLogo({
            transaction
        });
        
        
        output.favicon = await site_settings.getFavicon({
            transaction
        });
        
        
        output.brand_guidelines = await site_settings.getBrand_guidelines({
            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',
      },

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

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

    ];

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

            
            if (filter.site_name_ar) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'site_settings',
                        'site_name_ar',
                        filter.site_name_ar,
                    ),
                };
            }
            
            if (filter.site_tagline_ar) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'site_settings',
                        'site_tagline_ar',
                        filter.site_tagline_ar,
                    ),
                };
            }
            
            if (filter.primary_font) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'site_settings',
                        'primary_font',
                        filter.primary_font,
                    ),
                };
            }
            
            if (filter.primary_color_hex) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'site_settings',
                        'primary_color_hex',
                        filter.primary_color_hex,
                    ),
                };
            }
            
            if (filter.accent_color_hex) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'site_settings',
                        'accent_color_hex',
                        filter.accent_color_hex,
                    ),
                };
            }
            
            if (filter.seo_default_title_ar) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'site_settings',
                        'seo_default_title_ar',
                        filter.seo_default_title_ar,
                    ),
                };
            }
            
            if (filter.seo_default_description_ar) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'site_settings',
                        'seo_default_description_ar',
                        filter.seo_default_description_ar,
                    ),
                };
            }
            

            
            

            

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

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




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

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

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

    
};

