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

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

        const field_verifications = await db.field_verifications.create(
            {
                id: data.id || undefined,
        
        visit_date: data.visit_date
        ||
        null
            ,
            
        verification_type: data.verification_type
        ||
        null
            ,
            
        outcome: data.outcome
        ||
        null
            ,
            
        findings: data.findings
        ||
        null
            ,
            
        actions_required: data.actions_required
        ||
        null
            ,
            
        next_followup_at: data.next_followup_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await field_verifications.setProject( data.project || null, {
            transaction,
        });
        
        await field_verifications.setVerified_by_user( data.verified_by_user || null, {
            transaction,
        });
        
        await field_verifications.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

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

        return field_verifications;
    }
    

    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 field_verificationsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                visit_date: item.visit_date
            ||
            null
            ,
            
                verification_type: item.verification_type
            ||
            null
            ,
            
                outcome: item.outcome
            ||
            null
            ,
            
                findings: item.findings
            ||
            null
            ,
            
                actions_required: item.actions_required
            ||
            null
            ,
            
                next_followup_at: item.next_followup_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return field_verifications;
    }

    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 field_verifications = await db.field_verifications.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.visit_date !== undefined) updatePayload.visit_date = data.visit_date;
        
        
        if (data.verification_type !== undefined) updatePayload.verification_type = data.verification_type;
        
        
        if (data.outcome !== undefined) updatePayload.outcome = data.outcome;
        
        
        if (data.findings !== undefined) updatePayload.findings = data.findings;
        
        
        if (data.actions_required !== undefined) updatePayload.actions_required = data.actions_required;
        
        
        if (data.next_followup_at !== undefined) updatePayload.next_followup_at = data.next_followup_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.project !== undefined) {
            await field_verifications.setProject(
              
              data.project,
              
              { transaction }
            );
        }
        
        if (data.verified_by_user !== undefined) {
            await field_verifications.setVerified_by_user(
              
              data.verified_by_user,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await field_verifications.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

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

        return field_verifications;
    }

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

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

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


        return field_verifications;
    }

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

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

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

        await field_verifications.destroy({
            transaction
        });

        return field_verifications;
    }

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

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

        if (!field_verifications) {
            return field_verifications;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.project = await field_verifications.getProject({
            transaction
        });
        
        
        output.verified_by_user = await field_verifications.getVerified_by_user({
            transaction
        });
        
        
        output.photos = await field_verifications.getPhotos({
            transaction
        });
        
        
        output.organizations = await field_verifications.getOrganizations({
            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.projects,
        as: 'project',
        
        where: filter.project ? {
          [Op.or]: [
            { id: { [Op.in]: filter.project.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.project.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



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

    ];

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

            
            if (filter.findings) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'field_verifications',
                        'findings',
                        filter.findings,
                    ),
                };
            }
            
            if (filter.actions_required) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'field_verifications',
                        'actions_required',
                        filter.actions_required,
                    ),
                };
            }
            

            
            
            if (filter.calendarStart && filter.calendarEnd) {
                where = {
                    ...where,
                    [Op.or]: [
                        {
                            visit_date: {
                                [Op.between]: [filter.calendarStart, filter.calendarEnd],
                            },
                    },
                {
                    next_followup_at: {
                        [Op.between]: [filter.calendarStart, filter.calendarEnd],
                    },
                },
                ],
            };
            }
            

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

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

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

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

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

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

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


      

      

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

        where = {
          ...where,
          organizationsId: {[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.field_verifications.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(
                        'field_verifications',
                        'findings',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

