
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
            ,
            
        description: data.description
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        resolution: data.resolution
        ||
        null
            ,
            
        admin_notes: data.admin_notes
        ||
        null
            ,
            
        resolved_at: data.resolved_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await disputes.setBooking( data.booking || null, {
            transaction,
        });
        
        await disputes.setOpened_by( data.opened_by || null, {
            transaction,
        });
        
        await disputes.setResolved_by( data.resolved_by || null, {
            transaction,
        });
        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.disputes.getTableName(),
                belongsToColumn: 'tutor_evidence',
                belongsToId: disputes.id,
            },
            data.tutor_evidence,
            options,
        );
        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.disputes.getTableName(),
                belongsToColumn: 'learner_evidence',
                belongsToId: disputes.id,
            },
            data.learner_evidence,
            options,
        );
        

        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
            ,
            
                description: item.description
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                resolution: item.resolution
            ||
            null
            ,
            
                admin_notes: item.admin_notes
            ||
            null
            ,
            
                resolved_at: item.resolved_at
            ||
            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
        
        for (let i = 0; i < disputes.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.disputes.getTableName(),
                    belongsToColumn: 'tutor_evidence',
                    belongsToId: disputes[i].id,
                },
                data[i].tutor_evidence,
                options,
            );
        }
        
        for (let i = 0; i < disputes.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.disputes.getTableName(),
                    belongsToColumn: 'learner_evidence',
                    belongsToId: disputes[i].id,
                },
                data[i].learner_evidence,
                options,
            );
        }
        

        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.description !== undefined) updatePayload.description = data.description;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.resolution !== undefined) updatePayload.resolution = data.resolution;
        
        
        if (data.admin_notes !== undefined) updatePayload.admin_notes = data.admin_notes;
        
        
        if (data.resolved_at !== undefined) updatePayload.resolved_at = data.resolved_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.booking !== undefined) {
            await disputes.setBooking(
              
              data.booking,
              
              { transaction }
            );
        }
        
        if (data.opened_by !== undefined) {
            await disputes.setOpened_by(
              
              data.opened_by,
              
              { transaction }
            );
        }
        
        if (data.resolved_by !== undefined) {
            await disputes.setResolved_by(
              
              data.resolved_by,
              
              { transaction }
            );
        }
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.disputes.getTableName(),
                belongsToColumn: 'tutor_evidence',
                belongsToId: disputes.id,
            },
            data.tutor_evidence,
            options,
        );
        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.disputes.getTableName(),
                belongsToColumn: 'learner_evidence',
                belongsToId: disputes.id,
            },
            data.learner_evidence,
            options,
        );
        

        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.booking = await disputes.getBooking({
            transaction
        });
        
        
        output.opened_by = await disputes.getOpened_by({
            transaction
        });
        
        
        output.tutor_evidence = await disputes.getTutor_evidence({
            transaction
        });
        
        
        output.learner_evidence = await disputes.getLearner_evidence({
            transaction
        });
        
        
        output.resolved_by = await disputes.getResolved_by({
            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.bookings,
        as: 'booking',
        
        where: filter.booking ? {
          [Op.or]: [
            { id: { [Op.in]: filter.booking.split('|').map(term => Utils.uuid(term)) } },
            {
              level_name: {
                [Op.or]: filter.booking.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



      {
        model: db.file,
        as: 'tutor_evidence',
      },

      {
        model: db.file,
        as: 'learner_evidence',
      },

    ];

        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.description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'disputes',
                        'description',
                        filter.description,
                    ),
                };
            }
            
            if (filter.admin_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'disputes',
                        'admin_notes',
                        filter.admin_notes,
                    ),
                };
            }
            

            
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    resolved_at: {
                    ...where.resolved_at,
                            [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.resolution) {
                where = {
                    ...where,
                resolution: filter.resolution,
            };
            }
            


      

      

      



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

    
};

