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

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

        const trial_entries = await db.trial_entries.create(
            {
                id: data.id || undefined,
        
        entry_label: data.entry_label
        ||
        null
            ,
            
        entry_type: data.entry_type
        ||
        null
            ,
            
        treatment: data.treatment
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await trial_entries.setTrial( data.trial || null, {
            transaction,
        });
        
        await trial_entries.setVariety( data.variety || null, {
            transaction,
        });
        
        await trial_entries.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return trial_entries;
    }
    

    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 trial_entriesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                entry_label: item.entry_label
            ||
            null
            ,
            
                entry_type: item.entry_type
            ||
            null
            ,
            
                treatment: item.treatment
            ||
            null
            ,
            
                notes: item.notes
            ||
            null
            ,
            
                is_active: item.is_active
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return trial_entries;
    }

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


        

        const updatePayload = {};
        
        if (data.entry_label !== undefined) updatePayload.entry_label = data.entry_label;
        
        
        if (data.entry_type !== undefined) updatePayload.entry_type = data.entry_type;
        
        
        if (data.treatment !== undefined) updatePayload.treatment = data.treatment;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.trial !== undefined) {
            await trial_entries.setTrial(
              
              data.trial,
              
              { transaction }
            );
        }
        
        if (data.variety !== undefined) {
            await trial_entries.setVariety(
              
              data.variety,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await trial_entries.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return trial_entries;
    }

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

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

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


        return trial_entries;
    }

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

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

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

        await trial_entries.destroy({
            transaction
        });

        return trial_entries;
    }

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

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

        if (!trial_entries) {
            return trial_entries;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        output.plots_trial_entry = await trial_entries.getPlots_trial_entry({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        output.trial = await trial_entries.getTrial({
            transaction
        });
        
        
        output.variety = await trial_entries.getVariety({
            transaction
        });
        
        
        output.organizations = await trial_entries.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.trials,
        as: 'trial',
        
        where: filter.trial ? {
          [Op.or]: [
            { id: { [Op.in]: filter.trial.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.trial.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.varieties,
        as: 'variety',
        
        where: filter.variety ? {
          [Op.or]: [
            { id: { [Op.in]: filter.variety.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.variety.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.entry_label) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'trial_entries',
                        'entry_label',
                        filter.entry_label,
                    ),
                };
            }
            
            if (filter.treatment) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'trial_entries',
                        'treatment',
                        filter.treatment,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'trial_entries',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

            

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

            
            if (filter.entry_type) {
                where = {
                    ...where,
                entry_type: filter.entry_type,
            };
            }
            
            if (filter.is_active) {
                where = {
                    ...where,
                is_active: filter.is_active,
            };
            }
            


      

      

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

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

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

    
};

