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

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

        const matches = await db.matches.create(
            {
                id: data.id || undefined,
        
        matched_at: data.matched_at
        ||
        null
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
        last_message_at: data.last_message_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await matches.setUser_a( data.user_a || null, {
            transaction,
        });
        
        await matches.setUser_b( data.user_b || null, {
            transaction,
        });
        

        
        await matches.setMessages(data.messages || [], {
            transaction,
        });
        

        

        return matches;
    }
    

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

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

        // For each item created, replace relation files
        

        return matches;
    }

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

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


        

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

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

        
        
        if (data.user_a !== undefined) {
            await matches.setUser_a(
              
              data.user_a,
              
              { transaction }
            );
        }
        
        if (data.user_b !== undefined) {
            await matches.setUser_b(
              
              data.user_b,
              
              { transaction }
            );
        }
        

        
        
        if (data.messages !== undefined) {
            await matches.setMessages(data.messages, { transaction });
        }
        

        

        return matches;
    }

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

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

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


        return matches;
    }

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

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

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

        await matches.destroy({
            transaction
        });

        return matches;
    }

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

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

        if (!matches) {
            return matches;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        output.messages_match = await matches.getMessages_match({
            transaction
        });
        
        
        output.chat_events_match = await matches.getChat_events_match({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user_a = await matches.getUser_a({
            transaction
        });
        
        
        output.user_b = await matches.getUser_b({
            transaction
        });
        
        
        output.messages = await matches.getMessages({
            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: 'user_a',
        
        where: filter.user_a ? {
          [Op.or]: [
            { id: { [Op.in]: filter.user_a.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.user_a.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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


      {
        model: db.messages,
        as: 'messages',
        required: false,
      },


    ];

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

            

            
            

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

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

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

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

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

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

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


      

      


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

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

        

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

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

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

    
};

