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

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

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

        
        await post_saves.setPost( data.post || null, {
            transaction,
        });
        
        await post_saves.setUser( data.user || null, {
            transaction,
        });
        
        await post_saves.setCollection( data.collection || null, {
            transaction,
        });
        

        

        

        return post_saves;
    }
    

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

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

        // For each item created, replace relation files
        

        return post_saves;
    }

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

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


        

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

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

        
        
        if (data.post !== undefined) {
            await post_saves.setPost(
              
              data.post,
              
              { transaction }
            );
        }
        
        if (data.user !== undefined) {
            await post_saves.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        
        if (data.collection !== undefined) {
            await post_saves.setCollection(
              
              data.collection,
              
              { transaction }
            );
        }
        

        
        

        

        return post_saves;
    }

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

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

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


        return post_saves;
    }

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

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

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

        await post_saves.destroy({
            transaction
        });

        return post_saves;
    }

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

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

        if (!post_saves) {
            return post_saves;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.post = await post_saves.getPost({
            transaction
        });
        
        
        output.user = await post_saves.getUser({
            transaction
        });
        
        
        output.collection = await post_saves.getCollection({
            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.posts,
        as: 'post',
        
        where: filter.post ? {
          [Op.or]: [
            { id: { [Op.in]: filter.post.split('|').map(term => Utils.uuid(term)) } },
            {
              caption: {
                [Op.or]: filter.post.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



    ];

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

            

            
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    saved_at: {
                    ...where.saved_at,
                            [Op.lte]: end,
                    },
                };
                }
            }
            

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

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

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

    
};

