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

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

        const observations = await db.observations.create(
            {
                id: data.id || undefined,
        
        value_decimal: data.value_decimal
        ||
        null
            ,
            
        value_int: data.value_int
        ||
        null
            ,
            
        value_boolean: data.value_boolean
        ||
        false
        
            ,
            
        value_text: data.value_text
        ||
        null
            ,
            
        value_enum: data.value_enum
        ||
        null
            ,
            
        quality_flag: data.quality_flag
        ||
        null
            ,
            
        comment: data.comment
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await observations.setObservation_event( data.observation_event || null, {
            transaction,
        });
        
        await observations.setTrait( data.trait || null, {
            transaction,
        });
        
        await observations.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return observations;
    }
    

    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 observationsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                value_decimal: item.value_decimal
            ||
            null
            ,
            
                value_int: item.value_int
            ||
            null
            ,
            
                value_boolean: item.value_boolean
            ||
            false
        
            ,
            
                value_text: item.value_text
            ||
            null
            ,
            
                value_enum: item.value_enum
            ||
            null
            ,
            
                quality_flag: item.quality_flag
            ||
            null
            ,
            
                comment: item.comment
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return observations;
    }

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


        

        const updatePayload = {};
        
        if (data.value_decimal !== undefined) updatePayload.value_decimal = data.value_decimal;
        
        
        if (data.value_int !== undefined) updatePayload.value_int = data.value_int;
        
        
        if (data.value_boolean !== undefined) updatePayload.value_boolean = data.value_boolean;
        
        
        if (data.value_text !== undefined) updatePayload.value_text = data.value_text;
        
        
        if (data.value_enum !== undefined) updatePayload.value_enum = data.value_enum;
        
        
        if (data.quality_flag !== undefined) updatePayload.quality_flag = data.quality_flag;
        
        
        if (data.comment !== undefined) updatePayload.comment = data.comment;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.observation_event !== undefined) {
            await observations.setObservation_event(
              
              data.observation_event,
              
              { transaction }
            );
        }
        
        if (data.trait !== undefined) {
            await observations.setTrait(
              
              data.trait,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await observations.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return observations;
    }

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

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

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


        return observations;
    }

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

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

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

        await observations.destroy({
            transaction
        });

        return observations;
    }

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

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

        if (!observations) {
            return observations;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.observation_event = await observations.getObservation_event({
            transaction
        });
        
        
        output.trait = await observations.getTrait({
            transaction
        });
        
        
        output.organizations = await observations.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.observation_events,
        as: 'observation_event',
        
        where: filter.observation_event ? {
          [Op.or]: [
            { id: { [Op.in]: filter.observation_event.split('|').map(term => Utils.uuid(term)) } },
            {
              summary: {
                [Op.or]: filter.observation_event.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



    ];

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

            
            if (filter.value_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'observations',
                        'value_text',
                        filter.value_text,
                    ),
                };
            }
            
            if (filter.comment) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'observations',
                        'comment',
                        filter.comment,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

            
            if (filter.value_boolean) {
                where = {
                    ...where,
                value_boolean: filter.value_boolean,
            };
            }
            
            if (filter.value_enum) {
                where = {
                    ...where,
                value_enum: filter.value_enum,
            };
            }
            
            if (filter.quality_flag) {
                where = {
                    ...where,
                quality_flag: filter.quality_flag,
            };
            }
            


      

      

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

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

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

    
};

