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

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

        const service_requests = await db.service_requests.create(
            {
                id: data.id || undefined,
        
        category: data.category
        ||
        null
            ,
            
        priority: data.priority
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        title: data.title
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
        reported_at: data.reported_at
        ||
        null
            ,
            
        resolved_at: data.resolved_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await service_requests.setBooking( data.booking || null, {
            transaction,
        });
        
        await service_requests.setRoom( data.room || null, {
            transaction,
        });
        
        await service_requests.setReported_by( data.reported_by || null, {
            transaction,
        });
        
        await service_requests.setAssigned_to( data.assigned_to || null, {
            transaction,
        });
        

        

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

        return service_requests;
    }
    

    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 service_requestsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                category: item.category
            ||
            null
            ,
            
                priority: item.priority
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                title: item.title
            ||
            null
            ,
            
                description: item.description
            ||
            null
            ,
            
                reported_at: item.reported_at
            ||
            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 service_requests = await db.service_requests.bulkCreate(service_requestsData, { transaction });

        // For each item created, replace relation files
        
        for (let i = 0; i < service_requests.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.service_requests.getTableName(),
                    belongsToColumn: 'attachments',
                    belongsToId: service_requests[i].id,
                },
                data[i].attachments,
                options,
            );
        }
        

        return service_requests;
    }

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

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


        

        const updatePayload = {};
        
        if (data.category !== undefined) updatePayload.category = data.category;
        
        
        if (data.priority !== undefined) updatePayload.priority = data.priority;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.title !== undefined) updatePayload.title = data.title;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        if (data.reported_at !== undefined) updatePayload.reported_at = data.reported_at;
        
        
        if (data.resolved_at !== undefined) updatePayload.resolved_at = data.resolved_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.booking !== undefined) {
            await service_requests.setBooking(
              
              data.booking,
              
              { transaction }
            );
        }
        
        if (data.room !== undefined) {
            await service_requests.setRoom(
              
              data.room,
              
              { transaction }
            );
        }
        
        if (data.reported_by !== undefined) {
            await service_requests.setReported_by(
              
              data.reported_by,
              
              { transaction }
            );
        }
        
        if (data.assigned_to !== undefined) {
            await service_requests.setAssigned_to(
              
              data.assigned_to,
              
              { transaction }
            );
        }
        

        
        

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

        return service_requests;
    }

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

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

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


        return service_requests;
    }

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

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

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

        await service_requests.destroy({
            transaction
        });

        return service_requests;
    }

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

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

        if (!service_requests) {
            return service_requests;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.booking = await service_requests.getBooking({
            transaction
        });
        
        
        output.room = await service_requests.getRoom({
            transaction
        });
        
        
        output.reported_by = await service_requests.getReported_by({
            transaction
        });
        
        
        output.assigned_to = await service_requests.getAssigned_to({
            transaction
        });
        
        
        output.attachments = await service_requests.getAttachments({
            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)) } },
            {
              booking_code: {
                [Op.or]: filter.booking.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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

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



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

    ];

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

            
            if (filter.title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'service_requests',
                        'title',
                        filter.title,
                    ),
                };
            }
            
            if (filter.description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'service_requests',
                        'description',
                        filter.description,
                    ),
                };
            }
            

            
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    reported_at: {
                    ...where.reported_at,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            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.category) {
                where = {
                    ...where,
                category: filter.category,
            };
            }
            
            if (filter.priority) {
                where = {
                    ...where,
                priority: filter.priority,
            };
            }
            
            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.service_requests.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(
                        'service_requests',
                        'title',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

