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

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

        const content_assets = await db.content_assets.create(
            {
                id: data.id || undefined,
        
        asset_title: data.asset_title
        ||
        null
            ,
            
        asset_type: data.asset_type
        ||
        null
            ,
            
        body: data.body
        ||
        null
            ,
            
        asset_url: data.asset_url
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await content_assets.setOrganization(currentUser.organization.id || null, {
            transaction,
        });
        

        

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

        return content_assets;
    }
    

    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 content_assetsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                asset_title: item.asset_title
            ||
            null
            ,
            
                asset_type: item.asset_type
            ||
            null
            ,
            
                body: item.body
            ||
            null
            ,
            
                asset_url: item.asset_url
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return content_assets;
    }

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


        

        const updatePayload = {};
        
        if (data.asset_title !== undefined) updatePayload.asset_title = data.asset_title;
        
        
        if (data.asset_type !== undefined) updatePayload.asset_type = data.asset_type;
        
        
        if (data.body !== undefined) updatePayload.body = data.body;
        
        
        if (data.asset_url !== undefined) updatePayload.asset_url = data.asset_url;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.organization !== undefined) {
            await content_assets.setOrganization(
              
              (globalAccess ? data.organization : currentUser.organization.id),
              
              { transaction }
            );
        }
        

        
        

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

        return content_assets;
    }

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

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

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


        return content_assets;
    }

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

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

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

        await content_assets.destroy({
            transaction
        });

        return content_assets;
    }

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

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

        if (!content_assets) {
            return content_assets;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.organization = await content_assets.getOrganization({
            transaction
        });
        
        
        output.asset_files = await content_assets.getAsset_files({
            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.organizations,
        as: 'organization',
        
      },



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

    ];

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

            
            if (filter.asset_title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'content_assets',
                        'asset_title',
                        filter.asset_title,
                    ),
                };
            }
            
            if (filter.body) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'content_assets',
                        'body',
                        filter.body,
                    ),
                };
            }
            
            if (filter.asset_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'content_assets',
                        'asset_url',
                        filter.asset_url,
                    ),
                };
            }
            

            
            

            

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

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


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

        where = {
          ...where,
          organizationId: {[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.content_assets.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(
                        'content_assets',
                        'asset_title',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

