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

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

        const article_contents = await db.article_contents.create(
            {
                id: data.id || undefined,
        
        body: data.body
        ||
        null
            ,
            
        excerpt: data.excerpt
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await article_contents.setProduct( data.product || null, {
            transaction,
        });
        

        

        

        return article_contents;
    }
    

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

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

        // For each item created, replace relation files
        

        return article_contents;
    }

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

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


        

        const updatePayload = {};
        
        if (data.body !== undefined) updatePayload.body = data.body;
        
        
        if (data.excerpt !== undefined) updatePayload.excerpt = data.excerpt;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.product !== undefined) {
            await article_contents.setProduct(
              
              data.product,
              
              { transaction }
            );
        }
        

        
        

        

        return article_contents;
    }

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

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

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


        return article_contents;
    }

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

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

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

        await article_contents.destroy({
            transaction
        });

        return article_contents;
    }

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

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

        if (!article_contents) {
            return article_contents;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.product = await article_contents.getProduct({
            transaction
        });
        
        

        return output;
    }

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

        

        

        offset = currentPage * limit;

        const orderBy = null;

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

    let include = [

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



    ];

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

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

            
            

            

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

            


      



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

        

        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.article_contents.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, ) {
        let where = {};
        
        

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

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

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

    
};

