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

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

        const books = await db.books.create(
            {
                id: data.id || undefined,
        
        title: data.title
        ||
        null
            ,
            
        subtitle: data.subtitle
        ||
        null
            ,
            
        isbn: data.isbn
        ||
        null
            ,
            
        language: data.language
        ||
        null
            ,
            
        format: data.format
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
        page_count: data.page_count
        ||
        null
            ,
            
        word_count: data.word_count
        ||
        null
            ,
            
        duration_seconds: data.duration_seconds
        ||
        null
            ,
            
        difficulty_score: data.difficulty_score
        ||
        null
            ,
            
        popularity_score: data.popularity_score
        ||
        null
            ,
            
        published_at: data.published_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await books.setPublisher( data.publisher || null, {
            transaction,
        });
        

        
        await books.setAuthors(data.authors || [], {
            transaction,
        });
        
        await books.setGenres(data.genres || [], {
            transaction,
        });
        

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

        return books;
    }
    

    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 booksData = data.map((item, index) => ({
                id: item.id || undefined,
                
                title: item.title
            ||
            null
            ,
            
                subtitle: item.subtitle
            ||
            null
            ,
            
                isbn: item.isbn
            ||
            null
            ,
            
                language: item.language
            ||
            null
            ,
            
                format: item.format
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                description: item.description
            ||
            null
            ,
            
                page_count: item.page_count
            ||
            null
            ,
            
                word_count: item.word_count
            ||
            null
            ,
            
                duration_seconds: item.duration_seconds
            ||
            null
            ,
            
                difficulty_score: item.difficulty_score
            ||
            null
            ,
            
                popularity_score: item.popularity_score
            ||
            null
            ,
            
                published_at: item.published_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return books;
    }

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

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


        

        const updatePayload = {};
        
        if (data.title !== undefined) updatePayload.title = data.title;
        
        
        if (data.subtitle !== undefined) updatePayload.subtitle = data.subtitle;
        
        
        if (data.isbn !== undefined) updatePayload.isbn = data.isbn;
        
        
        if (data.language !== undefined) updatePayload.language = data.language;
        
        
        if (data.format !== undefined) updatePayload.format = data.format;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        if (data.page_count !== undefined) updatePayload.page_count = data.page_count;
        
        
        if (data.word_count !== undefined) updatePayload.word_count = data.word_count;
        
        
        if (data.duration_seconds !== undefined) updatePayload.duration_seconds = data.duration_seconds;
        
        
        if (data.difficulty_score !== undefined) updatePayload.difficulty_score = data.difficulty_score;
        
        
        if (data.popularity_score !== undefined) updatePayload.popularity_score = data.popularity_score;
        
        
        if (data.published_at !== undefined) updatePayload.published_at = data.published_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.publisher !== undefined) {
            await books.setPublisher(
              
              data.publisher,
              
              { transaction }
            );
        }
        

        
        
        if (data.authors !== undefined) {
            await books.setAuthors(data.authors, { transaction });
        }
        
        if (data.genres !== undefined) {
            await books.setGenres(data.genres, { transaction });
        }
        

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

        return books;
    }

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

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

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


        return books;
    }

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

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

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

        await books.destroy({
            transaction
        });

        return books;
    }

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

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

        if (!books) {
            return books;
        }

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

        
        
        
        
        
        
        
        
        output.user_library_items_book = await books.getUser_library_items_book({
            transaction
        });
        
        
        output.bookmarks_book = await books.getBookmarks_book({
            transaction
        });
        
        
        output.notes_book = await books.getNotes_book({
            transaction
        });
        
        
        output.camera_scan_sessions_book = await books.getCamera_scan_sessions_book({
            transaction
        });
        
        
        output.coin_ledger_entries_book = await books.getCoin_ledger_entries_book({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        output.quiz_definitions_book = await books.getQuiz_definitions_book({
            transaction
        });
        
        
        
        
        
        
        
        
        
        output.reading_circle_events_book = await books.getReading_circle_events_book({
            transaction
        });
        
        
        output.recommendation_events_book = await books.getRecommendation_events_book({
            transaction
        });
        
        
        
        
        
        
        
        output.cover_images = await books.getCover_images({
            transaction
        });
        
        
        output.content_files = await books.getContent_files({
            transaction
        });
        
        
        output.publisher = await books.getPublisher({
            transaction
        });
        
        
        output.authors = await books.getAuthors({
            transaction
        });
        
        
        output.genres = await books.getGenres({
            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.publishers,
        as: 'publisher',
        
        where: filter.publisher ? {
          [Op.or]: [
            { id: { [Op.in]: filter.publisher.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.publisher.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },


      {
        model: db.authors,
        as: 'authors',
        required: false,
      },

      {
        model: db.genres,
        as: 'genres',
        required: false,
      },


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

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

    ];

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

            
            if (filter.title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'books',
                        'title',
                        filter.title,
                    ),
                };
            }
            
            if (filter.subtitle) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'books',
                        'subtitle',
                        filter.subtitle,
                    ),
                };
            }
            
            if (filter.isbn) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'books',
                        'isbn',
                        filter.isbn,
                    ),
                };
            }
            
            if (filter.description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'books',
                        'description',
                        filter.description,
                    ),
                };
            }
            

            
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    page_count: {
                    ...where.page_count,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.word_countRange) {
                const [start, end] = filter.word_countRange;

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    word_count: {
                    ...where.word_count,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.duration_secondsRange) {
                const [start, end] = filter.duration_secondsRange;

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    duration_seconds: {
                    ...where.duration_seconds,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.difficulty_scoreRange) {
                const [start, end] = filter.difficulty_scoreRange;

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    difficulty_score: {
                    ...where.difficulty_score,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.popularity_scoreRange) {
                const [start, end] = filter.popularity_scoreRange;

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    popularity_score: {
                    ...where.popularity_score,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.published_atRange) {
                const [start, end] = filter.published_atRange;

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

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

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

            
            if (filter.language) {
                where = {
                    ...where,
                language: filter.language,
            };
            }
            
            if (filter.format) {
                where = {
                    ...where,
                format: filter.format,
            };
            }
            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            


      


      if (filter.authors) {
        const searchTerms = filter.authors.split('|');

        include = [
          {
            model: db.authors,
            as: 'authors_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  name: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }

      if (filter.genres) {
        const searchTerms = filter.genres.split('|');

        include = [
          {
            model: db.genres,
            as: 'genres_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  name: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }


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

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

    
};

