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

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

        const swipes = await db.swipes.create(
            {
                id: data.id || undefined,
        
        action: data.action
        ||
        null
            ,
            
        acted_at: data.acted_at
        ||
        null
            ,
            
        source: data.source
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await swipes.setFrom_user( data.from_user || null, {
            transaction,
        });
        
        await swipes.setTo_user( data.to_user || null, {
            transaction,
        });
        

        

        

        return swipes;
    }
    

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

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

        // For each item created, replace relation files
        

        return swipes;
    }

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

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


        

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

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

        
        
        if (data.from_user !== undefined) {
            await swipes.setFrom_user(
              
              data.from_user,
              
              { transaction }
            );
        }
        
        if (data.to_user !== undefined) {
            await swipes.setTo_user(
              
              data.to_user,
              
              { transaction }
            );
        }
        

        
        

        

        return swipes;
    }

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

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

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


        return swipes;
    }

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

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

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

        await swipes.destroy({
            transaction
        });

        return swipes;
    }

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

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

        if (!swipes) {
            return swipes;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.from_user = await swipes.getFrom_user({
            transaction
        });
        
        
        output.to_user = await swipes.getTo_user({
            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.users,
        as: 'from_user',
        
        where: filter.from_user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.from_user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.from_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

            
            if (filter.source) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'swipes',
                        'source',
                        filter.source,
                    ),
                };
            }
            

            
            

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

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

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

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

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


      

      



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

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

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

    
};

