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

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

        const user_library_items = await db.user_library_items.create(
            {
                id: data.id || undefined,
        
        source: data.source
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        offline_downloaded: data.offline_downloaded
        ||
        false
        
            ,
            
        downloaded_at: data.downloaded_at
        ||
        null
            ,
            
        progress_percent: data.progress_percent
        ||
        null
            ,
            
        current_location: data.current_location
        ||
        null
            ,
            
        last_opened_at: data.last_opened_at
        ||
        null
            ,
            
        completed_at: data.completed_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await user_library_items.setUser( data.user || null, {
            transaction,
        });
        
        await user_library_items.setBook( data.book || null, {
            transaction,
        });
        

        

        

        return user_library_items;
    }
    

    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 user_library_itemsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                source: item.source
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                offline_downloaded: item.offline_downloaded
            ||
            false
        
            ,
            
                downloaded_at: item.downloaded_at
            ||
            null
            ,
            
                progress_percent: item.progress_percent
            ||
            null
            ,
            
                current_location: item.current_location
            ||
            null
            ,
            
                last_opened_at: item.last_opened_at
            ||
            null
            ,
            
                completed_at: item.completed_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return user_library_items;
    }

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

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


        

        const updatePayload = {};
        
        if (data.source !== undefined) updatePayload.source = data.source;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.offline_downloaded !== undefined) updatePayload.offline_downloaded = data.offline_downloaded;
        
        
        if (data.downloaded_at !== undefined) updatePayload.downloaded_at = data.downloaded_at;
        
        
        if (data.progress_percent !== undefined) updatePayload.progress_percent = data.progress_percent;
        
        
        if (data.current_location !== undefined) updatePayload.current_location = data.current_location;
        
        
        if (data.last_opened_at !== undefined) updatePayload.last_opened_at = data.last_opened_at;
        
        
        if (data.completed_at !== undefined) updatePayload.completed_at = data.completed_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.user !== undefined) {
            await user_library_items.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        
        if (data.book !== undefined) {
            await user_library_items.setBook(
              
              data.book,
              
              { transaction }
            );
        }
        

        
        

        

        return user_library_items;
    }

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

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

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


        return user_library_items;
    }

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

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

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

        await user_library_items.destroy({
            transaction
        });

        return user_library_items;
    }

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

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

        if (!user_library_items) {
            return user_library_items;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await user_library_items.getUser({
            transaction
        });
        
        
        output.book = await user_library_items.getBook({
            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.users,
        as: 'user',
        
        where: filter.user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

            

            
            

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

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

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

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

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

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

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

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

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

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

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

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

            
            if (filter.source) {
                where = {
                    ...where,
                source: filter.source,
            };
            }
            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            
            if (filter.offline_downloaded) {
                where = {
                    ...where,
                offline_downloaded: filter.offline_downloaded,
            };
            }
            


      

      



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

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

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

    
};

