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

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

        const albums = await db.albums.create(
            {
                id: data.id || undefined,
        
        title: data.title
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
        privacy: data.privacy
        ||
        null
            ,
            
        collaboration_mode: data.collaboration_mode
        ||
        null
            ,
            
        allow_downloads: data.allow_downloads
        ||
        false
        
            ,
            
        allow_comments: data.allow_comments
        ||
        false
        
            ,
            
        allow_likes: data.allow_likes
        ||
        false
        
            ,
            
        allow_tagging: data.allow_tagging
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await albums.setEvent( data.event || null, {
            transaction,
        });
        
        await albums.setOwner( data.owner || null, {
            transaction,
        });
        
        await albums.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        
        await albums.setCollaborators(data.collaborators || [], {
            transaction,
        });
        
        await albums.setAccess_rules(data.access_rules || [], {
            transaction,
        });
        
        await albums.setShares(data.shares || [], {
            transaction,
        });
        
        await albums.setStories(data.stories || [], {
            transaction,
        });
        

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

        return albums;
    }
    

    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 albumsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                title: item.title
            ||
            null
            ,
            
                description: item.description
            ||
            null
            ,
            
                privacy: item.privacy
            ||
            null
            ,
            
                collaboration_mode: item.collaboration_mode
            ||
            null
            ,
            
                allow_downloads: item.allow_downloads
            ||
            false
        
            ,
            
                allow_comments: item.allow_comments
            ||
            false
        
            ,
            
                allow_likes: item.allow_likes
            ||
            false
        
            ,
            
                allow_tagging: item.allow_tagging
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return albums;
    }

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


        

        const updatePayload = {};
        
        if (data.title !== undefined) updatePayload.title = data.title;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        if (data.privacy !== undefined) updatePayload.privacy = data.privacy;
        
        
        if (data.collaboration_mode !== undefined) updatePayload.collaboration_mode = data.collaboration_mode;
        
        
        if (data.allow_downloads !== undefined) updatePayload.allow_downloads = data.allow_downloads;
        
        
        if (data.allow_comments !== undefined) updatePayload.allow_comments = data.allow_comments;
        
        
        if (data.allow_likes !== undefined) updatePayload.allow_likes = data.allow_likes;
        
        
        if (data.allow_tagging !== undefined) updatePayload.allow_tagging = data.allow_tagging;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.event !== undefined) {
            await albums.setEvent(
              
              data.event,
              
              { transaction }
            );
        }
        
        if (data.owner !== undefined) {
            await albums.setOwner(
              
              data.owner,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await albums.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        
        if (data.collaborators !== undefined) {
            await albums.setCollaborators(data.collaborators, { transaction });
        }
        
        if (data.access_rules !== undefined) {
            await albums.setAccess_rules(data.access_rules, { transaction });
        }
        
        if (data.shares !== undefined) {
            await albums.setShares(data.shares, { transaction });
        }
        
        if (data.stories !== undefined) {
            await albums.setStories(data.stories, { transaction });
        }
        

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

        return albums;
    }

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

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

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


        return albums;
    }

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

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

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

        await albums.destroy({
            transaction
        });

        return albums;
    }

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

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

        if (!albums) {
            return albums;
        }

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

        
        
        
        
        
        
        
        output.events_default_album = await albums.getEvents_default_album({
            transaction
        });
        
        
        
        output.album_collaborators_album = await albums.getAlbum_collaborators_album({
            transaction
        });
        
        
        output.access_rules_album = await albums.getAccess_rules_album({
            transaction
        });
        
        
        output.media_items_album = await albums.getMedia_items_album({
            transaction
        });
        
        
        
        
        output.upload_sessions_album = await albums.getUpload_sessions_album({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        output.notifications_album = await albums.getNotifications_album({
            transaction
        });
        
        
        
        output.shares_album = await albums.getShares_album({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        output.stories_album = await albums.getStories_album({
            transaction
        });
        
        
        
        output.analytics_events_album = await albums.getAnalytics_events_album({
            transaction
        });
        
        
        
        
        output.event = await albums.getEvent({
            transaction
        });
        
        
        output.owner = await albums.getOwner({
            transaction
        });
        
        
        output.cover_image = await albums.getCover_image({
            transaction
        });
        
        
        output.collaborators = await albums.getCollaborators({
            transaction
        });
        
        
        output.access_rules = await albums.getAccess_rules({
            transaction
        });
        
        
        output.shares = await albums.getShares({
            transaction
        });
        
        
        output.stories = await albums.getStories({
            transaction
        });
        
        
        output.organizations = await albums.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.events,
        as: 'event',
        
        where: filter.event ? {
          [Op.or]: [
            { id: { [Op.in]: filter.event.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.event.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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


      {
        model: db.album_collaborators,
        as: 'collaborators',
        required: false,
      },

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

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

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


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

    ];

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

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

            
            

            

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

            
            if (filter.privacy) {
                where = {
                    ...where,
                privacy: filter.privacy,
            };
            }
            
            if (filter.collaboration_mode) {
                where = {
                    ...where,
                collaboration_mode: filter.collaboration_mode,
            };
            }
            
            if (filter.allow_downloads) {
                where = {
                    ...where,
                allow_downloads: filter.allow_downloads,
            };
            }
            
            if (filter.allow_comments) {
                where = {
                    ...where,
                allow_comments: filter.allow_comments,
            };
            }
            
            if (filter.allow_likes) {
                where = {
                    ...where,
                allow_likes: filter.allow_likes,
            };
            }
            
            if (filter.allow_tagging) {
                where = {
                    ...where,
                allow_tagging: filter.allow_tagging,
            };
            }
            


      

      

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

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


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

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

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

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

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

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

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

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

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

    
};

