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

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

        const mock_trials = await db.mock_trials.create(
            {
                id: data.id || undefined,
        
        session_title: data.session_title
        ||
        null
            ,
            
        mode: data.mode
        ||
        null
            ,
            
        input_type: data.input_type
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        scheduled_at: data.scheduled_at
        ||
        null
            ,
            
        started_at: data.started_at
        ||
        null
            ,
            
        ended_at: data.ended_at
        ||
        null
            ,
            
        scenario_brief: data.scenario_brief
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await mock_trials.setOwner( data.owner || null, {
            transaction,
        });
        
        await mock_trials.setMatter( data.matter || null, {
            transaction,
        });
        

        

        

        return mock_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 mock_trialsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                session_title: item.session_title
            ||
            null
            ,
            
                mode: item.mode
            ||
            null
            ,
            
                input_type: item.input_type
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                scheduled_at: item.scheduled_at
            ||
            null
            ,
            
                started_at: item.started_at
            ||
            null
            ,
            
                ended_at: item.ended_at
            ||
            null
            ,
            
                scenario_brief: item.scenario_brief
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return mock_trials;
    }

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

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


        

        const updatePayload = {};
        
        if (data.session_title !== undefined) updatePayload.session_title = data.session_title;
        
        
        if (data.mode !== undefined) updatePayload.mode = data.mode;
        
        
        if (data.input_type !== undefined) updatePayload.input_type = data.input_type;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.scheduled_at !== undefined) updatePayload.scheduled_at = data.scheduled_at;
        
        
        if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
        
        
        if (data.ended_at !== undefined) updatePayload.ended_at = data.ended_at;
        
        
        if (data.scenario_brief !== undefined) updatePayload.scenario_brief = data.scenario_brief;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.owner !== undefined) {
            await mock_trials.setOwner(
              
              data.owner,
              
              { transaction }
            );
        }
        
        if (data.matter !== undefined) {
            await mock_trials.setMatter(
              
              data.matter,
              
              { transaction }
            );
        }
        

        
        

        

        return mock_trials;
    }

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

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

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


        return mock_trials;
    }

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

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

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

        await mock_trials.destroy({
            transaction
        });

        return mock_trials;
    }

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

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

        if (!mock_trials) {
            return mock_trials;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.mock_trial_roles_mock_trial = await mock_trials.getMock_trial_roles_mock_trial({
            transaction
        });
        
        
        output.mock_trial_turns_mock_trial = await mock_trials.getMock_trial_turns_mock_trial({
            transaction
        });
        
        
        
        
        
        
        
        
        output.owner = await mock_trials.getOwner({
            transaction
        });
        
        
        output.matter = await mock_trials.getMatter({
            transaction
        });
        
        

        return output;
    }

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

        

        

        offset = currentPage * limit;

        const orderBy = null;

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

    let include = [

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

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



    ];

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

            
            if (filter.session_title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'mock_trials',
                        'session_title',
                        filter.session_title,
                    ),
                };
            }
            
            if (filter.scenario_brief) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'mock_trials',
                        'scenario_brief',
                        filter.scenario_brief,
                    ),
                };
            }
            

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

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

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

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

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

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

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

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

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

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


      

      



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

        

        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.mock_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, ) {
        let where = {};
        
        

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

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

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

    
};

