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

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

        const problem_reports = await db.problem_reports.create(
            {
                id: data.id || undefined,
        
        title: data.title
        ||
        null
            ,
            
        scope: data.scope
        ||
        null
            ,
            
        category: data.category
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
        evidence_links: data.evidence_links
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        submitted_at: data.submitted_at
        ||
        null
            ,
            
        published_at: data.published_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await problem_reports.setAuthor( data.author || null, {
            transaction,
        });
        
        await problem_reports.setOrganization(currentUser.organization.id || null, {
            transaction,
        });
        

        

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

        return problem_reports;
    }
    

    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 problem_reportsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                title: item.title
            ||
            null
            ,
            
                scope: item.scope
            ||
            null
            ,
            
                category: item.category
            ||
            null
            ,
            
                description: item.description
            ||
            null
            ,
            
                evidence_links: item.evidence_links
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                submitted_at: item.submitted_at
            ||
            null
            ,
            
                published_at: item.published_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return problem_reports;
    }

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

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


        

        const updatePayload = {};
        
        if (data.title !== undefined) updatePayload.title = data.title;
        
        
        if (data.scope !== undefined) updatePayload.scope = data.scope;
        
        
        if (data.category !== undefined) updatePayload.category = data.category;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        if (data.evidence_links !== undefined) updatePayload.evidence_links = data.evidence_links;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.submitted_at !== undefined) updatePayload.submitted_at = data.submitted_at;
        
        
        if (data.published_at !== undefined) updatePayload.published_at = data.published_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.author !== undefined) {
            await problem_reports.setAuthor(
              
              data.author,
              
              { transaction }
            );
        }
        
        if (data.organization !== undefined) {
            await problem_reports.setOrganization(
              
              (globalAccess ? data.organization : currentUser.organization.id),
              
              { transaction }
            );
        }
        

        
        

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

        return problem_reports;
    }

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

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

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


        return problem_reports;
    }

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

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

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

        await problem_reports.destroy({
            transaction
        });

        return problem_reports;
    }

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

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

        if (!problem_reports) {
            return problem_reports;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.solution_proposals_problem_report = await problem_reports.getSolution_proposals_problem_report({
            transaction
        });
        
        
        output.votes_problem_report = await problem_reports.getVotes_problem_report({
            transaction
        });
        
        
        output.comments_problem_report = await problem_reports.getComments_problem_report({
            transaction
        });
        
        
        
        
        
        
        
        
        
        output.images = await problem_reports.getImages({
            transaction
        });
        
        
        output.attachments = await problem_reports.getAttachments({
            transaction
        });
        
        
        output.author = await problem_reports.getAuthor({
            transaction
        });
        
        
        output.organization = await problem_reports.getOrganization({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           globalAccess,  options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        
        const user = (options && options.currentUser) || null;
        const userOrganizations = (user && user.organizations?.id) || null;
        

        
        if (userOrganizations) {
            if (options?.currentUser?.organizationsId) {
                where.organizationsId = options.currentUser.organizationsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

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

      {
        model: db.organizations,
        as: 'organization',
        
      },



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

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

            
            

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

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

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

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

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

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

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


      

      
      if (filter.organization) {
        const listItems = filter.organization.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          organizationId: {[Op.or]: listItems}
        };
      }
      



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

        
        if (globalAccess) {
            delete where.organizationsId;
        }
        

        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.problem_reports.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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'problem_reports',
                        'title',
                        query,
                    ),
                ],
            };
        }

        const records = await db.problem_reports.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,
        }));
    }

    
};

