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

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

        const disputes = await db.disputes.create(
            {
                id: data.id || undefined,
        
        reason: data.reason
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        resolution_notes: data.resolution_notes
        ||
        null
            ,
            
        created_at_ts: data.created_at_ts
        ||
        null
            ,
            
        updated_at_ts: data.updated_at_ts
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await disputes.setLead( data.lead || null, {
            transaction,
        });
        
        await disputes.setOpened_by_user( data.opened_by_user || null, {
            transaction,
        });
        

        

        

        return disputes;
    }
    

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

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

        // For each item created, replace relation files
        

        return disputes;
    }

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

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


        

        const updatePayload = {};
        
        if (data.reason !== undefined) updatePayload.reason = data.reason;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.resolution_notes !== undefined) updatePayload.resolution_notes = data.resolution_notes;
        
        
        if (data.created_at_ts !== undefined) updatePayload.created_at_ts = data.created_at_ts;
        
        
        if (data.updated_at_ts !== undefined) updatePayload.updated_at_ts = data.updated_at_ts;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.lead !== undefined) {
            await disputes.setLead(
              
              data.lead,
              
              { transaction }
            );
        }
        
        if (data.opened_by_user !== undefined) {
            await disputes.setOpened_by_user(
              
              data.opened_by_user,
              
              { transaction }
            );
        }
        

        
        

        

        return disputes;
    }

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

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

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


        return disputes;
    }

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

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

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

        await disputes.destroy({
            transaction
        });

        return disputes;
    }

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

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

        if (!disputes) {
            return disputes;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.lead = await disputes.getLead({
            transaction
        });
        
        
        output.opened_by_user = await disputes.getOpened_by_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.leads,
        as: 'lead',
        
        where: filter.lead ? {
          [Op.or]: [
            { id: { [Op.in]: filter.lead.split('|').map(term => Utils.uuid(term)) } },
            {
              keyword: {
                [Op.or]: filter.lead.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

            
            if (filter.reason) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'disputes',
                        'reason',
                        filter.reason,
                    ),
                };
            }
            
            if (filter.resolution_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'disputes',
                        'resolution_notes',
                        filter.resolution_notes,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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


      

      



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

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

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

    
};

