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

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

        const database_entries = await db.database_entries.create(
            {
                id: data.id || undefined,
        
        title: data.title
        ||
        null
            ,
            
        summary: data.summary
        ||
        null
            ,
            
        content_type: data.content_type
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        studied_at: data.studied_at
        ||
        null
            ,
            
        next_review_at: data.next_review_at
        ||
        null
            ,
            
        estimated_retention: data.estimated_retention
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await database_entries.setDatabase( data.database || null, {
            transaction,
        });
        
        await database_entries.setSubject( data.subject || null, {
            transaction,
        });
        
        await database_entries.setTopic( data.topic || null, {
            transaction,
        });
        
        await database_entries.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

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

        return database_entries;
    }
    

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

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

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

        return database_entries;
    }

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

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


        

        const updatePayload = {};
        
        if (data.title !== undefined) updatePayload.title = data.title;
        
        
        if (data.summary !== undefined) updatePayload.summary = data.summary;
        
        
        if (data.content_type !== undefined) updatePayload.content_type = data.content_type;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.studied_at !== undefined) updatePayload.studied_at = data.studied_at;
        
        
        if (data.next_review_at !== undefined) updatePayload.next_review_at = data.next_review_at;
        
        
        if (data.estimated_retention !== undefined) updatePayload.estimated_retention = data.estimated_retention;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.database !== undefined) {
            await database_entries.setDatabase(
              
              data.database,
              
              { transaction }
            );
        }
        
        if (data.subject !== undefined) {
            await database_entries.setSubject(
              
              data.subject,
              
              { transaction }
            );
        }
        
        if (data.topic !== undefined) {
            await database_entries.setTopic(
              
              data.topic,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await database_entries.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

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

        return database_entries;
    }

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

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

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


        return database_entries;
    }

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

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

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

        await database_entries.destroy({
            transaction
        });

        return database_entries;
    }

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

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

        if (!database_entries) {
            return database_entries;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.database = await database_entries.getDatabase({
            transaction
        });
        
        
        output.subject = await database_entries.getSubject({
            transaction
        });
        
        
        output.topic = await database_entries.getTopic({
            transaction
        });
        
        
        output.attachments = await database_entries.getAttachments({
            transaction
        });
        
        
        output.organizations = await database_entries.getOrganizations({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           globalAccess,  options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        
        const user = (options && options.currentUser) || null;
        const userOrganizations = (user && user.organizations?.id) || null;
        

        
        if (userOrganizations) {
            if (options?.currentUser?.organizationsId) {
                where.organizationsId = options.currentUser.organizationsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

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

      {
        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.topics,
        as: 'topic',
        
        where: filter.topic ? {
          [Op.or]: [
            { id: { [Op.in]: filter.topic.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.topic.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.organizations,
        as: 'organizations',
        
      },



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

    ];

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

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

            
            

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

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

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

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

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

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

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

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

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


      

      

      

      
      if (filter.organizations) {
        const listItems = filter.organizations.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          organizationsId: {[Op.or]: listItems}
        };
      }
      



            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,
                        },
                    };
                }
            }
        }
        

        
        if (globalAccess) {
            delete where.organizationsId;
        }
        

        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.database_entries.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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'database_entries',
                        'title',
                        query,
                    ),
                ],
            };
        }

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

    
};

