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

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

        const upload_sessions = await db.upload_sessions.create(
            {
                id: data.id || undefined,
        
        status: data.status
        ||
        null
            ,
            
        total_files: data.total_files
        ||
        null
            ,
            
        completed_files: data.completed_files
        ||
        null
            ,
            
        failed_files: data.failed_files
        ||
        null
            ,
            
        started_at: data.started_at
        ||
        null
            ,
            
        completed_at: data.completed_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await upload_sessions.setAlbum( data.album || null, {
            transaction,
        });
        
        await upload_sessions.setInitiator( data.initiator || null, {
            transaction,
        });
        
        await upload_sessions.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        
        await upload_sessions.setUpload_files(data.upload_files || [], {
            transaction,
        });
        

        

        return upload_sessions;
    }
    

    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 upload_sessionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                status: item.status
            ||
            null
            ,
            
                total_files: item.total_files
            ||
            null
            ,
            
                completed_files: item.completed_files
            ||
            null
            ,
            
                failed_files: item.failed_files
            ||
            null
            ,
            
                started_at: item.started_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 upload_sessions = await db.upload_sessions.bulkCreate(upload_sessionsData, { transaction });

        // For each item created, replace relation files
        

        return upload_sessions;
    }

    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 upload_sessions = await db.upload_sessions.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.total_files !== undefined) updatePayload.total_files = data.total_files;
        
        
        if (data.completed_files !== undefined) updatePayload.completed_files = data.completed_files;
        
        
        if (data.failed_files !== undefined) updatePayload.failed_files = data.failed_files;
        
        
        if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
        
        
        if (data.completed_at !== undefined) updatePayload.completed_at = data.completed_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.album !== undefined) {
            await upload_sessions.setAlbum(
              
              data.album,
              
              { transaction }
            );
        }
        
        if (data.initiator !== undefined) {
            await upload_sessions.setInitiator(
              
              data.initiator,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await upload_sessions.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        
        if (data.upload_files !== undefined) {
            await upload_sessions.setUpload_files(data.upload_files, { transaction });
        }
        

        

        return upload_sessions;
    }

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

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

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


        return upload_sessions;
    }

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

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

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

        await upload_sessions.destroy({
            transaction
        });

        return upload_sessions;
    }

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

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

        if (!upload_sessions) {
            return upload_sessions;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.upload_files_upload_session = await upload_sessions.getUpload_files_upload_session({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.album = await upload_sessions.getAlbum({
            transaction
        });
        
        
        output.initiator = await upload_sessions.getInitiator({
            transaction
        });
        
        
        output.upload_files = await upload_sessions.getUpload_files({
            transaction
        });
        
        
        output.organizations = await upload_sessions.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.albums,
        as: 'album',
        
        where: filter.album ? {
          [Op.or]: [
            { id: { [Op.in]: filter.album.split('|').map(term => Utils.uuid(term)) } },
            {
              title: {
                [Op.or]: filter.album.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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


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


    ];

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

            

            
            

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

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

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    started_at: {
                    ...where.started_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.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.upload_files) {
        const searchTerms = filter.upload_files.split('|');

        include = [
          {
            model: db.upload_files,
            as: 'upload_files_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  file_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,
                        },
                    };
                }
            }
        }
        

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

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

    
};

