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

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

        const dialogue_lines = await db.dialogue_lines.create(
            {
                id: data.id || undefined,
        
        line_text: data.line_text
        ||
        null
            ,
            
        mood_tag: data.mood_tag
        ||
        null
            ,
            
        priority: data.priority
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await dialogue_lines.setTopic( data.topic || null, {
            transaction,
        });
        
        await dialogue_lines.setNpc( data.npc || null, {
            transaction,
        });
        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.dialogue_lines.getTableName(),
                belongsToColumn: 'voice_files',
                belongsToId: dialogue_lines.id,
            },
            data.voice_files,
            options,
        );
        

        return dialogue_lines;
    }
    

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

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

        // For each item created, replace relation files
        
        for (let i = 0; i < dialogue_lines.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.dialogue_lines.getTableName(),
                    belongsToColumn: 'voice_files',
                    belongsToId: dialogue_lines[i].id,
                },
                data[i].voice_files,
                options,
            );
        }
        

        return dialogue_lines;
    }

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

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


        

        const updatePayload = {};
        
        if (data.line_text !== undefined) updatePayload.line_text = data.line_text;
        
        
        if (data.mood_tag !== undefined) updatePayload.mood_tag = data.mood_tag;
        
        
        if (data.priority !== undefined) updatePayload.priority = data.priority;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.topic !== undefined) {
            await dialogue_lines.setTopic(
              
              data.topic,
              
              { transaction }
            );
        }
        
        if (data.npc !== undefined) {
            await dialogue_lines.setNpc(
              
              data.npc,
              
              { transaction }
            );
        }
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.dialogue_lines.getTableName(),
                belongsToColumn: 'voice_files',
                belongsToId: dialogue_lines.id,
            },
            data.voice_files,
            options,
        );
        

        return dialogue_lines;
    }

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

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

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


        return dialogue_lines;
    }

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

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

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

        await dialogue_lines.destroy({
            transaction
        });

        return dialogue_lines;
    }

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

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

        if (!dialogue_lines) {
            return dialogue_lines;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.topic = await dialogue_lines.getTopic({
            transaction
        });
        
        
        output.npc = await dialogue_lines.getNpc({
            transaction
        });
        
        
        output.voice_files = await dialogue_lines.getVoice_files({
            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.dialogue_topics,
        as: 'topic',
        
        where: filter.topic ? {
          [Op.or]: [
            { id: { [Op.in]: filter.topic.split('|').map(term => Utils.uuid(term)) } },
            {
              title: {
                [Op.or]: filter.topic.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



      {
        model: db.file,
        as: 'voice_files',
      },

    ];

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

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

            
            

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

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

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

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

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


      

      



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

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

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

    
};

