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

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

        const content_items = await db.content_items.create(
            {
                id: data.id || undefined,
        
        title: data.title
        ||
        null
            ,
            
        content_type: data.content_type
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        body: data.body
        ||
        null
            ,
            
        summary: data.summary
        ||
        null
            ,
            
        scheduled_at: data.scheduled_at
        ||
        null
            ,
            
        published_at: data.published_at
        ||
        null
            ,
            
        channel: data.channel
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await content_items.setCompany( data.company || null, {
            transaction,
        });
        
        await content_items.setBusiness_unit( data.business_unit || null, {
            transaction,
        });
        
        await content_items.setFolder( data.folder || null, {
            transaction,
        });
        
        await content_items.setOwner( data.owner || null, {
            transaction,
        });
        

        
        await content_items.setTags(data.tags || [], {
            transaction,
        });
        

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

        return content_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 content_itemsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                title: item.title
            ||
            null
            ,
            
                content_type: item.content_type
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                body: item.body
            ||
            null
            ,
            
                summary: item.summary
            ||
            null
            ,
            
                scheduled_at: item.scheduled_at
            ||
            null
            ,
            
                published_at: item.published_at
            ||
            null
            ,
            
                channel: item.channel
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return content_items;
    }

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


        

        const updatePayload = {};
        
        if (data.title !== undefined) updatePayload.title = data.title;
        
        
        if (data.content_type !== undefined) updatePayload.content_type = data.content_type;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.body !== undefined) updatePayload.body = data.body;
        
        
        if (data.summary !== undefined) updatePayload.summary = data.summary;
        
        
        if (data.scheduled_at !== undefined) updatePayload.scheduled_at = data.scheduled_at;
        
        
        if (data.published_at !== undefined) updatePayload.published_at = data.published_at;
        
        
        if (data.channel !== undefined) updatePayload.channel = data.channel;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.company !== undefined) {
            await content_items.setCompany(
              
              data.company,
              
              { transaction }
            );
        }
        
        if (data.business_unit !== undefined) {
            await content_items.setBusiness_unit(
              
              data.business_unit,
              
              { transaction }
            );
        }
        
        if (data.folder !== undefined) {
            await content_items.setFolder(
              
              data.folder,
              
              { transaction }
            );
        }
        
        if (data.owner !== undefined) {
            await content_items.setOwner(
              
              data.owner,
              
              { transaction }
            );
        }
        

        
        
        if (data.tags !== undefined) {
            await content_items.setTags(data.tags, { transaction });
        }
        

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

        return content_items;
    }

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

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

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


        return content_items;
    }

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

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

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

        await content_items.destroy({
            transaction
        });

        return content_items;
    }

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

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

        if (!content_items) {
            return content_items;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.company = await content_items.getCompany({
            transaction
        });
        
        
        output.business_unit = await content_items.getBusiness_unit({
            transaction
        });
        
        
        output.folder = await content_items.getFolder({
            transaction
        });
        
        
        output.owner = await content_items.getOwner({
            transaction
        });
        
        
        output.attachments = await content_items.getAttachments({
            transaction
        });
        
        
        output.tags = await content_items.getTags({
            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 userCompanies = (user && user.companies?.id) || null;
        

        
        if (userCompanies) {
            if (options?.currentUser?.companiesId) {
                where.companiesId = options.currentUser.companiesId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

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

    let include = [

      {
        model: db.companies,
        as: 'company',
        
      },

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

      {
        model: db.content_folders,
        as: 'folder',
        
        where: filter.folder ? {
          [Op.or]: [
            { id: { [Op.in]: filter.folder.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.folder.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.tags,
        as: 'tags',
        required: false,
      },


      {
        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(
                        'content_items',
                        'title',
                        filter.title,
                    ),
                };
            }
            
            if (filter.body) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'content_items',
                        'body',
                        filter.body,
                    ),
                };
            }
            
            if (filter.summary) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'content_items',
                        'summary',
                        filter.summary,
                    ),
                };
            }
            
            if (filter.channel) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'content_items',
                        'channel',
                        filter.channel,
                    ),
                };
            }
            

            
            

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    published_at: {
                    ...where.published_at,
                            [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.company) {
        const listItems = filter.company.split('|').map(item => {
          return  Utils.uuid(item)
        });

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

      

      

      


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

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

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

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

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

    
};

