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

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

        const transcription_jobs = await db.transcription_jobs.create(
            {
                id: data.id || undefined,
        
        status: data.status
        ||
        null
            ,
            
        source_language: data.source_language
        ||
        null
            ,
            
        target_language: data.target_language
        ||
        null
            ,
            
        speaker_diarization: data.speaker_diarization
        ||
        false
        
            ,
            
        confidence_avg: data.confidence_avg
        ||
        null
            ,
            
        transcript_text: data.transcript_text
        ||
        null
            ,
            
        summary_text: data.summary_text
        ||
        null
            ,
            
        started_at: data.started_at
        ||
        null
            ,
            
        finished_at: data.finished_at
        ||
        null
            ,
            
        error_message: data.error_message
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await transcription_jobs.setRequested_by( data.requested_by || null, {
            transaction,
        });
        
        await transcription_jobs.setMatter( data.matter || null, {
            transaction,
        });
        
        await transcription_jobs.setMedia_file( data.media_file || null, {
            transaction,
        });
        
        await transcription_jobs.setExport_file( data.export_file || null, {
            transaction,
        });
        

        

        

        return transcription_jobs;
    }
    

    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 transcription_jobsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                status: item.status
            ||
            null
            ,
            
                source_language: item.source_language
            ||
            null
            ,
            
                target_language: item.target_language
            ||
            null
            ,
            
                speaker_diarization: item.speaker_diarization
            ||
            false
        
            ,
            
                confidence_avg: item.confidence_avg
            ||
            null
            ,
            
                transcript_text: item.transcript_text
            ||
            null
            ,
            
                summary_text: item.summary_text
            ||
            null
            ,
            
                started_at: item.started_at
            ||
            null
            ,
            
                finished_at: item.finished_at
            ||
            null
            ,
            
                error_message: item.error_message
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return transcription_jobs;
    }

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

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


        

        const updatePayload = {};
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.source_language !== undefined) updatePayload.source_language = data.source_language;
        
        
        if (data.target_language !== undefined) updatePayload.target_language = data.target_language;
        
        
        if (data.speaker_diarization !== undefined) updatePayload.speaker_diarization = data.speaker_diarization;
        
        
        if (data.confidence_avg !== undefined) updatePayload.confidence_avg = data.confidence_avg;
        
        
        if (data.transcript_text !== undefined) updatePayload.transcript_text = data.transcript_text;
        
        
        if (data.summary_text !== undefined) updatePayload.summary_text = data.summary_text;
        
        
        if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
        
        
        if (data.finished_at !== undefined) updatePayload.finished_at = data.finished_at;
        
        
        if (data.error_message !== undefined) updatePayload.error_message = data.error_message;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.requested_by !== undefined) {
            await transcription_jobs.setRequested_by(
              
              data.requested_by,
              
              { transaction }
            );
        }
        
        if (data.matter !== undefined) {
            await transcription_jobs.setMatter(
              
              data.matter,
              
              { transaction }
            );
        }
        
        if (data.media_file !== undefined) {
            await transcription_jobs.setMedia_file(
              
              data.media_file,
              
              { transaction }
            );
        }
        
        if (data.export_file !== undefined) {
            await transcription_jobs.setExport_file(
              
              data.export_file,
              
              { transaction }
            );
        }
        

        
        

        

        return transcription_jobs;
    }

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

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

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


        return transcription_jobs;
    }

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

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

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

        await transcription_jobs.destroy({
            transaction
        });

        return transcription_jobs;
    }

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

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

        if (!transcription_jobs) {
            return transcription_jobs;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.requested_by = await transcription_jobs.getRequested_by({
            transaction
        });
        
        
        output.matter = await transcription_jobs.getMatter({
            transaction
        });
        
        
        output.media_file = await transcription_jobs.getMedia_file({
            transaction
        });
        
        
        output.export_file = await transcription_jobs.getExport_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.users,
        as: 'requested_by',
        
        where: filter.requested_by ? {
          [Op.or]: [
            { id: { [Op.in]: filter.requested_by.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.requested_by.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}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



    ];

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

            
            if (filter.source_language) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'transcription_jobs',
                        'source_language',
                        filter.source_language,
                    ),
                };
            }
            
            if (filter.target_language) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'transcription_jobs',
                        'target_language',
                        filter.target_language,
                    ),
                };
            }
            
            if (filter.transcript_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'transcription_jobs',
                        'transcript_text',
                        filter.transcript_text,
                    ),
                };
            }
            
            if (filter.summary_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'transcription_jobs',
                        'summary_text',
                        filter.summary_text,
                    ),
                };
            }
            
            if (filter.error_message) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'transcription_jobs',
                        'error_message',
                        filter.error_message,
                    ),
                };
            }
            

            
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    confidence_avg: {
                    ...where.confidence_avg,
                            [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.finished_atRange) {
                const [start, end] = filter.finished_atRange;

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    finished_at: {
                    ...where.finished_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.speaker_diarization) {
                where = {
                    ...where,
                speaker_diarization: filter.speaker_diarization,
            };
            }
            


      

      

      

      



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

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

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

    
};

