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

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

        const textbooks = await db.textbooks.create(
            {
                id: data.id || undefined,
        
        title: data.title
        ||
        null
            ,
            
        publisher: data.publisher
        ||
        null
            ,
            
        edition: data.edition
        ||
        null
            ,
            
        isbn: data.isbn
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await textbooks.setSubject( data.subject || null, {
            transaction,
        });
        
        await textbooks.setGrade_level( data.grade_level || null, {
            transaction,
        });
        

        

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

        return textbooks;
    }
    

    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 textbooksData = data.map((item, index) => ({
                id: item.id || undefined,
                
                title: item.title
            ||
            null
            ,
            
                publisher: item.publisher
            ||
            null
            ,
            
                edition: item.edition
            ||
            null
            ,
            
                isbn: item.isbn
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return textbooks;
    }

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

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


        

        const updatePayload = {};
        
        if (data.title !== undefined) updatePayload.title = data.title;
        
        
        if (data.publisher !== undefined) updatePayload.publisher = data.publisher;
        
        
        if (data.edition !== undefined) updatePayload.edition = data.edition;
        
        
        if (data.isbn !== undefined) updatePayload.isbn = data.isbn;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.subject !== undefined) {
            await textbooks.setSubject(
              
              data.subject,
              
              { transaction }
            );
        }
        
        if (data.grade_level !== undefined) {
            await textbooks.setGrade_level(
              
              data.grade_level,
              
              { transaction }
            );
        }
        

        
        

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

        return textbooks;
    }

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

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

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


        return textbooks;
    }

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

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

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

        await textbooks.destroy({
            transaction
        });

        return textbooks;
    }

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

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

        if (!textbooks) {
            return textbooks;
        }

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

        
        
        
        
        
        
        
        output.chapters_textbook = await textbooks.getChapters_textbook({
            transaction
        });
        
        
        
        
        output.question_banks_textbook = await textbooks.getQuestion_banks_textbook({
            transaction
        });
        
        
        
        
        output.tests_textbook = await textbooks.getTests_textbook({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.subject = await textbooks.getSubject({
            transaction
        });
        
        
        output.grade_level = await textbooks.getGrade_level({
            transaction
        });
        
        
        output.source_files = await textbooks.getSource_files({
            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.subjects,
        as: 'subject',
        
        where: filter.subject ? {
          [Op.or]: [
            { id: { [Op.in]: filter.subject.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.subject.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.grade_levels,
        as: 'grade_level',
        
        where: filter.grade_level ? {
          [Op.or]: [
            { id: { [Op.in]: filter.grade_level.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.grade_level.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



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

    ];

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

            
            if (filter.title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'textbooks',
                        'title',
                        filter.title,
                    ),
                };
            }
            
            if (filter.publisher) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'textbooks',
                        'publisher',
                        filter.publisher,
                    ),
                };
            }
            
            if (filter.edition) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'textbooks',
                        'edition',
                        filter.edition,
                    ),
                };
            }
            
            if (filter.isbn) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'textbooks',
                        'isbn',
                        filter.isbn,
                    ),
                };
            }
            

            
            

            

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

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

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

    
};

