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

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

        const subject_categories = await db.subject_categories.create(
            {
                id: data.id || undefined,
        
        name_bn: data.name_bn
        ||
        null
            ,
            
        name_en: data.name_en
        ||
        null
            ,
            
        icon_key: data.icon_key
        ||
        null
            ,
            
        seed_tutor_count: data.seed_tutor_count
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

        

        return subject_categories;
    }
    

    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 subject_categoriesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name_bn: item.name_bn
            ||
            null
            ,
            
                name_en: item.name_en
            ||
            null
            ,
            
                icon_key: item.icon_key
            ||
            null
            ,
            
                seed_tutor_count: item.seed_tutor_count
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return subject_categories;
    }

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

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


        

        const updatePayload = {};
        
        if (data.name_bn !== undefined) updatePayload.name_bn = data.name_bn;
        
        
        if (data.name_en !== undefined) updatePayload.name_en = data.name_en;
        
        
        if (data.icon_key !== undefined) updatePayload.icon_key = data.icon_key;
        
        
        if (data.seed_tutor_count !== undefined) updatePayload.seed_tutor_count = data.seed_tutor_count;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        

        

        return subject_categories;
    }

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

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

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


        return subject_categories;
    }

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

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

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

        await subject_categories.destroy({
            transaction
        });

        return subject_categories;
    }

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

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

        if (!subject_categories) {
            return subject_categories;
        }

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

        
        
        
        
        
        
        
        output.subjects_category = await subject_categories.getSubjects_category({
            transaction
        });
        
        
        
        output.gigs_category = await subject_categories.getGigs_category({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.spaces_category = await subject_categories.getSpaces_category({
            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 = [



    ];

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

            
            if (filter.name_bn) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'subject_categories',
                        'name_bn',
                        filter.name_bn,
                    ),
                };
            }
            
            if (filter.name_en) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'subject_categories',
                        'name_en',
                        filter.name_en,
                    ),
                };
            }
            
            if (filter.icon_key) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'subject_categories',
                        'icon_key',
                        filter.icon_key,
                    ),
                };
            }
            

            
            

            
            if (filter.seed_tutor_countRange) {
                const [start, end] = filter.seed_tutor_countRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                    seed_tutor_count: {
                    ...where.seed_tutor_count,
                            [Op.gte]: start,
                    },
                };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    seed_tutor_count: {
                    ...where.seed_tutor_count,
                            [Op.lte]: end,
                    },
                };
                }
            }
            

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

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

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

    
};

