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

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

        const trade_attachments = await db.trade_attachments.create(
            {
                id: data.id || undefined,
        
        attachment_type: data.attachment_type
        ||
        null
            ,
            
        caption: data.caption
        ||
        null
            ,
            
        captured_at: data.captured_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await trade_attachments.setTrade( data.trade || null, {
            transaction,
        });
        

        

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

        return trade_attachments;
    }
    

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

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

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

        return trade_attachments;
    }

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

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


        

        const updatePayload = {};
        
        if (data.attachment_type !== undefined) updatePayload.attachment_type = data.attachment_type;
        
        
        if (data.caption !== undefined) updatePayload.caption = data.caption;
        
        
        if (data.captured_at !== undefined) updatePayload.captured_at = data.captured_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.trade !== undefined) {
            await trade_attachments.setTrade(
              
              data.trade,
              
              { transaction }
            );
        }
        

        
        

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

        return trade_attachments;
    }

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

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

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


        return trade_attachments;
    }

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

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

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

        await trade_attachments.destroy({
            transaction
        });

        return trade_attachments;
    }

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

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

        if (!trade_attachments) {
            return trade_attachments;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.trade = await trade_attachments.getTrade({
            transaction
        });
        
        
        output.images = await trade_attachments.getImages({
            transaction
        });
        
        
        output.files = await trade_attachments.getFiles({
            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.trades,
        as: 'trade',
        
        where: filter.trade ? {
          [Op.or]: [
            { id: { [Op.in]: filter.trade.split('|').map(term => Utils.uuid(term)) } },
            {
              notes: {
                [Op.or]: filter.trade.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



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

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

    ];

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

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

            
            

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

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

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

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

            
            if (filter.attachment_type) {
                where = {
                    ...where,
                attachment_type: filter.attachment_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.trade_attachments.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(
                        'trade_attachments',
                        'caption',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

