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

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

        const chapters = await db.chapters.create(
            {
                id: data.id || undefined,
        
        title: data.title
        ||
        null
            ,
            
        chapter_number: data.chapter_number
        ||
        null
            ,
            
        sort_order: data.sort_order
        ||
        null
            ,
            
        summary: data.summary
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await chapters.setTextbook( data.textbook || null, {
            transaction,
        });
        

        

        

        return chapters;
    }
    

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

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

        // For each item created, replace relation files
        

        return chapters;
    }

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

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


        

        const updatePayload = {};
        
        if (data.title !== undefined) updatePayload.title = data.title;
        
        
        if (data.chapter_number !== undefined) updatePayload.chapter_number = data.chapter_number;
        
        
        if (data.sort_order !== undefined) updatePayload.sort_order = data.sort_order;
        
        
        if (data.summary !== undefined) updatePayload.summary = data.summary;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.textbook !== undefined) {
            await chapters.setTextbook(
              
              data.textbook,
              
              { transaction }
            );
        }
        

        
        

        

        return chapters;
    }

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

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

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


        return chapters;
    }

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

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

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

        await chapters.destroy({
            transaction
        });

        return chapters;
    }

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

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

        if (!chapters) {
            return chapters;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        output.questions_chapter = await chapters.getQuestions_chapter({
            transaction
        });
        
        
        
        output.tests_chapter = await chapters.getTests_chapter({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.ai_generation_jobs_chapter = await chapters.getAi_generation_jobs_chapter({
            transaction
        });
        
        
        
        output.textbook = await chapters.getTextbook({
            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.textbooks,
        as: 'textbook',
        
        where: filter.textbook ? {
          [Op.or]: [
            { id: { [Op.in]: filter.textbook.split('|').map(term => Utils.uuid(term)) } },
            {
              title: {
                [Op.or]: filter.textbook.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'chapters',
                        'title',
                        filter.title,
                    ),
                };
            }
            
            if (filter.chapter_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'chapters',
                        'chapter_number',
                        filter.chapter_number,
                    ),
                };
            }
            
            if (filter.summary) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'chapters',
                        'summary',
                        filter.summary,
                    ),
                };
            }
            

            
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    sort_order: {
                    ...where.sort_order,
                            [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.chapters.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(
                        'chapters',
                        'title',
                        query,
                    ),
                ],
            };
        }

        const records = await db.chapters.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,
        }));
    }

    
};

