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

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

        const ai_jobs = await db.ai_jobs.create(
            {
                id: data.id || undefined,
        
        job_type: data.job_type
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        input_summary: data.input_summary
        ||
        null
            ,
            
        output_summary: data.output_summary
        ||
        null
            ,
            
        cost_usd: data.cost_usd
        ||
        null
            ,
            
        queued_at: data.queued_at
        ||
        null
            ,
            
        started_at: data.started_at
        ||
        null
            ,
            
        completed_at: data.completed_at
        ||
        null
            ,
            
        error_message: data.error_message
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await ai_jobs.setRequested_by( data.requested_by || null, {
            transaction,
        });
        
        await ai_jobs.setMatter( data.matter || null, {
            transaction,
        });
        
        await ai_jobs.setFile( data.file || null, {
            transaction,
        });
        

        

        

        return ai_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 ai_jobsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                job_type: item.job_type
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                input_summary: item.input_summary
            ||
            null
            ,
            
                output_summary: item.output_summary
            ||
            null
            ,
            
                cost_usd: item.cost_usd
            ||
            null
            ,
            
                queued_at: item.queued_at
            ||
            null
            ,
            
                started_at: item.started_at
            ||
            null
            ,
            
                completed_at: item.completed_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 ai_jobs = await db.ai_jobs.bulkCreate(ai_jobsData, { transaction });

        // For each item created, replace relation files
        

        return ai_jobs;
    }

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

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


        

        const updatePayload = {};
        
        if (data.job_type !== undefined) updatePayload.job_type = data.job_type;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.input_summary !== undefined) updatePayload.input_summary = data.input_summary;
        
        
        if (data.output_summary !== undefined) updatePayload.output_summary = data.output_summary;
        
        
        if (data.cost_usd !== undefined) updatePayload.cost_usd = data.cost_usd;
        
        
        if (data.queued_at !== undefined) updatePayload.queued_at = data.queued_at;
        
        
        if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
        
        
        if (data.completed_at !== undefined) updatePayload.completed_at = data.completed_at;
        
        
        if (data.error_message !== undefined) updatePayload.error_message = data.error_message;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.requested_by !== undefined) {
            await ai_jobs.setRequested_by(
              
              data.requested_by,
              
              { transaction }
            );
        }
        
        if (data.matter !== undefined) {
            await ai_jobs.setMatter(
              
              data.matter,
              
              { transaction }
            );
        }
        
        if (data.file !== undefined) {
            await ai_jobs.setFile(
              
              data.file,
              
              { transaction }
            );
        }
        

        
        

        

        return ai_jobs;
    }

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

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

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


        return ai_jobs;
    }

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

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

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

        await ai_jobs.destroy({
            transaction
        });

        return ai_jobs;
    }

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

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

        if (!ai_jobs) {
            return ai_jobs;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.requested_by = await ai_jobs.getRequested_by({
            transaction
        });
        
        
        output.matter = await ai_jobs.getMatter({
            transaction
        });
        
        
        output.file = await ai_jobs.getFile({
            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: 'file',
        
        where: filter.file ? {
          [Op.or]: [
            { id: { [Op.in]: filter.file.split('|').map(term => Utils.uuid(term)) } },
            {
              file_name: {
                [Op.or]: filter.file.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.input_summary) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ai_jobs',
                        'input_summary',
                        filter.input_summary,
                    ),
                };
            }
            
            if (filter.output_summary) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ai_jobs',
                        'output_summary',
                        filter.output_summary,
                    ),
                };
            }
            
            if (filter.error_message) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ai_jobs',
                        'error_message',
                        filter.error_message,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

            
            if (filter.job_type) {
                where = {
                    ...where,
                job_type: filter.job_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.ai_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(
                        'ai_jobs',
                        'job_type',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

