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

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

        const generation_requests = await db.generation_requests.create(
            {
                id: data.id || undefined,
        
        request_type: data.request_type
        ||
        null
            ,
            
        prompt_text: data.prompt_text
        ||
        null
            ,
            
        target_bpm: data.target_bpm
        ||
        null
            ,
            
        target_key: data.target_key
        ||
        null
            ,
            
        mood: data.mood
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        queued_at: data.queued_at
        ||
        null
            ,
            
        started_at: data.started_at
        ||
        null
            ,
            
        finished_at: data.finished_at
        ||
        null
            ,
            
        error_message: data.error_message
        ||
        null
            ,
            
        compute_seconds: data.compute_seconds
        ||
        null
            ,
            
        estimated_cost: data.estimated_cost
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await generation_requests.setWorkspace( data.workspace || null, {
            transaction,
        });
        
        await generation_requests.setProject( data.project || null, {
            transaction,
        });
        
        await generation_requests.setSong( data.song || null, {
            transaction,
        });
        
        await generation_requests.setRequested_user( data.requested_user || null, {
            transaction,
        });
        
        await generation_requests.setModel( data.model || null, {
            transaction,
        });
        
        await generation_requests.setInput_asset( data.input_asset || null, {
            transaction,
        });
        
        await generation_requests.setTarget_genre( data.target_genre || null, {
            transaction,
        });
        
        await generation_requests.setOutput_asset( data.output_asset || null, {
            transaction,
        });
        
        await generation_requests.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return generation_requests;
    }
    

    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 generation_requestsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                request_type: item.request_type
            ||
            null
            ,
            
                prompt_text: item.prompt_text
            ||
            null
            ,
            
                target_bpm: item.target_bpm
            ||
            null
            ,
            
                target_key: item.target_key
            ||
            null
            ,
            
                mood: item.mood
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                queued_at: item.queued_at
            ||
            null
            ,
            
                started_at: item.started_at
            ||
            null
            ,
            
                finished_at: item.finished_at
            ||
            null
            ,
            
                error_message: item.error_message
            ||
            null
            ,
            
                compute_seconds: item.compute_seconds
            ||
            null
            ,
            
                estimated_cost: item.estimated_cost
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return generation_requests;
    }

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


        

        const updatePayload = {};
        
        if (data.request_type !== undefined) updatePayload.request_type = data.request_type;
        
        
        if (data.prompt_text !== undefined) updatePayload.prompt_text = data.prompt_text;
        
        
        if (data.target_bpm !== undefined) updatePayload.target_bpm = data.target_bpm;
        
        
        if (data.target_key !== undefined) updatePayload.target_key = data.target_key;
        
        
        if (data.mood !== undefined) updatePayload.mood = data.mood;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.queued_at !== undefined) updatePayload.queued_at = data.queued_at;
        
        
        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;
        
        
        if (data.compute_seconds !== undefined) updatePayload.compute_seconds = data.compute_seconds;
        
        
        if (data.estimated_cost !== undefined) updatePayload.estimated_cost = data.estimated_cost;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.workspace !== undefined) {
            await generation_requests.setWorkspace(
              
              data.workspace,
              
              { transaction }
            );
        }
        
        if (data.project !== undefined) {
            await generation_requests.setProject(
              
              data.project,
              
              { transaction }
            );
        }
        
        if (data.song !== undefined) {
            await generation_requests.setSong(
              
              data.song,
              
              { transaction }
            );
        }
        
        if (data.requested_user !== undefined) {
            await generation_requests.setRequested_user(
              
              data.requested_user,
              
              { transaction }
            );
        }
        
        if (data.model !== undefined) {
            await generation_requests.setModel(
              
              data.model,
              
              { transaction }
            );
        }
        
        if (data.input_asset !== undefined) {
            await generation_requests.setInput_asset(
              
              data.input_asset,
              
              { transaction }
            );
        }
        
        if (data.target_genre !== undefined) {
            await generation_requests.setTarget_genre(
              
              data.target_genre,
              
              { transaction }
            );
        }
        
        if (data.output_asset !== undefined) {
            await generation_requests.setOutput_asset(
              
              data.output_asset,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await generation_requests.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return generation_requests;
    }

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

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

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


        return generation_requests;
    }

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

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

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

        await generation_requests.destroy({
            transaction
        });

        return generation_requests;
    }

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

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

        if (!generation_requests) {
            return generation_requests;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.workspace = await generation_requests.getWorkspace({
            transaction
        });
        
        
        output.project = await generation_requests.getProject({
            transaction
        });
        
        
        output.song = await generation_requests.getSong({
            transaction
        });
        
        
        output.requested_user = await generation_requests.getRequested_user({
            transaction
        });
        
        
        output.model = await generation_requests.getModel({
            transaction
        });
        
        
        output.input_asset = await generation_requests.getInput_asset({
            transaction
        });
        
        
        output.target_genre = await generation_requests.getTarget_genre({
            transaction
        });
        
        
        output.output_asset = await generation_requests.getOutput_asset({
            transaction
        });
        
        
        output.organizations = await generation_requests.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.workspaces,
        as: 'workspace',
        
        where: filter.workspace ? {
          [Op.or]: [
            { id: { [Op.in]: filter.workspace.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.workspace.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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

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

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

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

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

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

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



    ];

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

            
            if (filter.prompt_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'generation_requests',
                        'prompt_text',
                        filter.prompt_text,
                    ),
                };
            }
            
            if (filter.target_key) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'generation_requests',
                        'target_key',
                        filter.target_key,
                    ),
                };
            }
            
            if (filter.error_message) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'generation_requests',
                        'error_message',
                        filter.error_message,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

            
            if (filter.request_type) {
                where = {
                    ...where,
                request_type: filter.request_type,
            };
            }
            
            if (filter.mood) {
                where = {
                    ...where,
                mood: filter.mood,
            };
            }
            
            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.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.generation_requests.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(
                        'generation_requests',
                        'request_type',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

