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

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

        const school_settings = await db.school_settings.create(
            {
                id: data.id || undefined,
        
        school_name_om: data.school_name_om
        ||
        null
            ,
            
        school_name_am: data.school_name_am
        ||
        null
            ,
            
        school_name_en: data.school_name_en
        ||
        null
            ,
            
        welcome_message_om: data.welcome_message_om
        ||
        null
            ,
            
        welcome_message_am: data.welcome_message_am
        ||
        null
            ,
            
        welcome_message_en: data.welcome_message_en
        ||
        null
            ,
            
        address_text: data.address_text
        ||
        null
            ,
            
        map_embed_url: data.map_embed_url
        ||
        null
            ,
            
        public_phone_numbers: data.public_phone_numbers
        ||
        null
            ,
            
        public_emails: data.public_emails
        ||
        null
            ,
            
        social_links: data.social_links
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

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

        return school_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 school_settingsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                school_name_om: item.school_name_om
            ||
            null
            ,
            
                school_name_am: item.school_name_am
            ||
            null
            ,
            
                school_name_en: item.school_name_en
            ||
            null
            ,
            
                welcome_message_om: item.welcome_message_om
            ||
            null
            ,
            
                welcome_message_am: item.welcome_message_am
            ||
            null
            ,
            
                welcome_message_en: item.welcome_message_en
            ||
            null
            ,
            
                address_text: item.address_text
            ||
            null
            ,
            
                map_embed_url: item.map_embed_url
            ||
            null
            ,
            
                public_phone_numbers: item.public_phone_numbers
            ||
            null
            ,
            
                public_emails: item.public_emails
            ||
            null
            ,
            
                social_links: item.social_links
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return school_settings;
    }

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

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


        

        const updatePayload = {};
        
        if (data.school_name_om !== undefined) updatePayload.school_name_om = data.school_name_om;
        
        
        if (data.school_name_am !== undefined) updatePayload.school_name_am = data.school_name_am;
        
        
        if (data.school_name_en !== undefined) updatePayload.school_name_en = data.school_name_en;
        
        
        if (data.welcome_message_om !== undefined) updatePayload.welcome_message_om = data.welcome_message_om;
        
        
        if (data.welcome_message_am !== undefined) updatePayload.welcome_message_am = data.welcome_message_am;
        
        
        if (data.welcome_message_en !== undefined) updatePayload.welcome_message_en = data.welcome_message_en;
        
        
        if (data.address_text !== undefined) updatePayload.address_text = data.address_text;
        
        
        if (data.map_embed_url !== undefined) updatePayload.map_embed_url = data.map_embed_url;
        
        
        if (data.public_phone_numbers !== undefined) updatePayload.public_phone_numbers = data.public_phone_numbers;
        
        
        if (data.public_emails !== undefined) updatePayload.public_emails = data.public_emails;
        
        
        if (data.social_links !== undefined) updatePayload.social_links = data.social_links;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        

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

        return school_settings;
    }

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

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

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


        return school_settings;
    }

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

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

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

        await school_settings.destroy({
            transaction
        });

        return school_settings;
    }

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

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

        if (!school_settings) {
            return school_settings;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.logo = await school_settings.getLogo({
            transaction
        });
        
        
        output.hero_images = await school_settings.getHero_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',
      },

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

    ];

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

            
            if (filter.school_name_om) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'school_settings',
                        'school_name_om',
                        filter.school_name_om,
                    ),
                };
            }
            
            if (filter.school_name_am) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'school_settings',
                        'school_name_am',
                        filter.school_name_am,
                    ),
                };
            }
            
            if (filter.school_name_en) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'school_settings',
                        'school_name_en',
                        filter.school_name_en,
                    ),
                };
            }
            
            if (filter.welcome_message_om) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'school_settings',
                        'welcome_message_om',
                        filter.welcome_message_om,
                    ),
                };
            }
            
            if (filter.welcome_message_am) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'school_settings',
                        'welcome_message_am',
                        filter.welcome_message_am,
                    ),
                };
            }
            
            if (filter.welcome_message_en) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'school_settings',
                        'welcome_message_en',
                        filter.welcome_message_en,
                    ),
                };
            }
            
            if (filter.address_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'school_settings',
                        'address_text',
                        filter.address_text,
                    ),
                };
            }
            
            if (filter.map_embed_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'school_settings',
                        'map_embed_url',
                        filter.map_embed_url,
                    ),
                };
            }
            
            if (filter.public_phone_numbers) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'school_settings',
                        'public_phone_numbers',
                        filter.public_phone_numbers,
                    ),
                };
            }
            
            if (filter.public_emails) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'school_settings',
                        'public_emails',
                        filter.public_emails,
                    ),
                };
            }
            
            if (filter.social_links) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'school_settings',
                        'social_links',
                        filter.social_links,
                    ),
                };
            }
            

            
            

            

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

            




            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.school_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(
                        'school_settings',
                        'school_name_en',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

