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

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

        const trials = await db.trials.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        code: data.code
        ||
        null
            ,
            
        objective: data.objective
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        planned_start_at: data.planned_start_at
        ||
        null
            ,
            
        planned_end_at: data.planned_end_at
        ||
        null
            ,
            
        actual_start_at: data.actual_start_at
        ||
        null
            ,
            
        actual_end_at: data.actual_end_at
        ||
        null
            ,
            
        protocol_notes: data.protocol_notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await trials.setTenant( data.tenant || null, {
            transaction,
        });
        
        await trials.setFarm( data.farm || null, {
            transaction,
        });
        
        await trials.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        
        await trials.setTrial_sites(data.trial_sites || [], {
            transaction,
        });
        
        await trials.setTrial_entries(data.trial_entries || [], {
            transaction,
        });
        

        

        return trials;
    }
    

    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 trialsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                code: item.code
            ||
            null
            ,
            
                objective: item.objective
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                planned_start_at: item.planned_start_at
            ||
            null
            ,
            
                planned_end_at: item.planned_end_at
            ||
            null
            ,
            
                actual_start_at: item.actual_start_at
            ||
            null
            ,
            
                actual_end_at: item.actual_end_at
            ||
            null
            ,
            
                protocol_notes: item.protocol_notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return trials;
    }

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.code !== undefined) updatePayload.code = data.code;
        
        
        if (data.objective !== undefined) updatePayload.objective = data.objective;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.planned_start_at !== undefined) updatePayload.planned_start_at = data.planned_start_at;
        
        
        if (data.planned_end_at !== undefined) updatePayload.planned_end_at = data.planned_end_at;
        
        
        if (data.actual_start_at !== undefined) updatePayload.actual_start_at = data.actual_start_at;
        
        
        if (data.actual_end_at !== undefined) updatePayload.actual_end_at = data.actual_end_at;
        
        
        if (data.protocol_notes !== undefined) updatePayload.protocol_notes = data.protocol_notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.tenant !== undefined) {
            await trials.setTenant(
              
              data.tenant,
              
              { transaction }
            );
        }
        
        if (data.farm !== undefined) {
            await trials.setFarm(
              
              data.farm,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await trials.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        
        if (data.trial_sites !== undefined) {
            await trials.setTrial_sites(data.trial_sites, { transaction });
        }
        
        if (data.trial_entries !== undefined) {
            await trials.setTrial_entries(data.trial_entries, { transaction });
        }
        

        

        return trials;
    }

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

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

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


        return trials;
    }

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

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

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

        await trials.destroy({
            transaction
        });

        return trials;
    }

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

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

        if (!trials) {
            return trials;
        }

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

        
        
        
        
        
        
        
        
        output.trial_sites_trial = await trials.getTrial_sites_trial({
            transaction
        });
        
        
        
        output.trial_entries_trial = await trials.getTrial_entries_trial({
            transaction
        });
        
        
        
        
        output.observation_events_trial = await trials.getObservation_events_trial({
            transaction
        });
        
        
        
        
        
        
        output.reports_trial = await trials.getReports_trial({
            transaction
        });
        
        
        
        
        output.tenant = await trials.getTenant({
            transaction
        });
        
        
        output.farm = await trials.getFarm({
            transaction
        });
        
        
        output.trial_sites = await trials.getTrial_sites({
            transaction
        });
        
        
        output.trial_entries = await trials.getTrial_entries({
            transaction
        });
        
        
        output.organizations = await trials.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.tenants,
        as: 'tenant',
        
        where: filter.tenant ? {
          [Op.or]: [
            { id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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


      {
        model: db.trial_sites,
        as: 'trial_sites',
        required: false,
      },

      {
        model: db.trial_entries,
        as: 'trial_entries',
        required: false,
      },


    ];

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

            
            if (filter.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'trials',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'trials',
                        'code',
                        filter.code,
                    ),
                };
            }
            
            if (filter.objective) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'trials',
                        'objective',
                        filter.objective,
                    ),
                };
            }
            
            if (filter.protocol_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'trials',
                        'protocol_notes',
                        filter.protocol_notes,
                    ),
                };
            }
            

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

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

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

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

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

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

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

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

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

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

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

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


      

      

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

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


      if (filter.trial_sites) {
        const searchTerms = filter.trial_sites.split('|');

        include = [
          {
            model: db.trial_sites,
            as: 'trial_sites_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  name: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }

      if (filter.trial_entries) {
        const searchTerms = filter.trial_entries.split('|');

        include = [
          {
            model: db.trial_entries,
            as: 'trial_entries_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  entry_label: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }


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

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

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

    
};

