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

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

        const mock_trial_turns = await db.mock_trial_turns.create(
            {
                id: data.id || undefined,
        
        turn_type: data.turn_type
        ||
        null
            ,
            
        content: data.content
        ||
        null
            ,
            
        spoken_at: data.spoken_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await mock_trial_turns.setMock_trial( data.mock_trial || null, {
            transaction,
        });
        
        await mock_trial_turns.setRole( data.role || null, {
            transaction,
        });
        
        await mock_trial_turns.setAudio_file( data.audio_file || null, {
            transaction,
        });
        

        

        

        return mock_trial_turns;
    }
    

    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_trial_turnsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                turn_type: item.turn_type
            ||
            null
            ,
            
                content: item.content
            ||
            null
            ,
            
                spoken_at: item.spoken_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return mock_trial_turns;
    }

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

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


        

        const updatePayload = {};
        
        if (data.turn_type !== undefined) updatePayload.turn_type = data.turn_type;
        
        
        if (data.content !== undefined) updatePayload.content = data.content;
        
        
        if (data.spoken_at !== undefined) updatePayload.spoken_at = data.spoken_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.mock_trial !== undefined) {
            await mock_trial_turns.setMock_trial(
              
              data.mock_trial,
              
              { transaction }
            );
        }
        
        if (data.role !== undefined) {
            await mock_trial_turns.setRole(
              
              data.role,
              
              { transaction }
            );
        }
        
        if (data.audio_file !== undefined) {
            await mock_trial_turns.setAudio_file(
              
              data.audio_file,
              
              { transaction }
            );
        }
        

        
        

        

        return mock_trial_turns;
    }

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

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

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


        return mock_trial_turns;
    }

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

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

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

        await mock_trial_turns.destroy({
            transaction
        });

        return mock_trial_turns;
    }

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

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

        if (!mock_trial_turns) {
            return mock_trial_turns;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.mock_trial = await mock_trial_turns.getMock_trial({
            transaction
        });
        
        
        output.role = await mock_trial_turns.getRole({
            transaction
        });
        
        
        output.audio_file = await mock_trial_turns.getAudio_file({
            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.mock_trials,
        as: 'mock_trial',
        
        where: filter.mock_trial ? {
          [Op.or]: [
            { id: { [Op.in]: filter.mock_trial.split('|').map(term => Utils.uuid(term)) } },
            {
              session_title: {
                [Op.or]: filter.mock_trial.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



    ];

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

            
            if (filter.content) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'mock_trial_turns',
                        'content',
                        filter.content,
                    ),
                };
            }
            

            
            

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

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

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

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

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


      

      

      



            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_trial_turns.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_trial_turns',
                        'turn_type',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

