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

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

        const letters_of_credit = await db.letters_of_credit.create(
            {
                id: data.id || undefined,
        
        lc_number: data.lc_number
        ||
        null
            ,
            
        issue_date: data.issue_date
        ||
        null
            ,
            
        expiry_date: data.expiry_date
        ||
        null
            ,
            
        amount: data.amount
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await letters_of_credit.setBusiness( data.business || null, {
            transaction,
        });
        
        await letters_of_credit.setBank( data.bank || null, {
            transaction,
        });
        
        await letters_of_credit.setCounterparty( data.counterparty || null, {
            transaction,
        });
        
        await letters_of_credit.setCurrency( data.currency || null, {
            transaction,
        });
        

        

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

        return letters_of_credit;
    }
    

    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 letters_of_creditData = data.map((item, index) => ({
                id: item.id || undefined,
                
                lc_number: item.lc_number
            ||
            null
            ,
            
                issue_date: item.issue_date
            ||
            null
            ,
            
                expiry_date: item.expiry_date
            ||
            null
            ,
            
                amount: item.amount
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return letters_of_credit;
    }

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

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


        

        const updatePayload = {};
        
        if (data.lc_number !== undefined) updatePayload.lc_number = data.lc_number;
        
        
        if (data.issue_date !== undefined) updatePayload.issue_date = data.issue_date;
        
        
        if (data.expiry_date !== undefined) updatePayload.expiry_date = data.expiry_date;
        
        
        if (data.amount !== undefined) updatePayload.amount = data.amount;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.business !== undefined) {
            await letters_of_credit.setBusiness(
              
              data.business,
              
              { transaction }
            );
        }
        
        if (data.bank !== undefined) {
            await letters_of_credit.setBank(
              
              data.bank,
              
              { transaction }
            );
        }
        
        if (data.counterparty !== undefined) {
            await letters_of_credit.setCounterparty(
              
              data.counterparty,
              
              { transaction }
            );
        }
        
        if (data.currency !== undefined) {
            await letters_of_credit.setCurrency(
              
              data.currency,
              
              { transaction }
            );
        }
        

        
        

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

        return letters_of_credit;
    }

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

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

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


        return letters_of_credit;
    }

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

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

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

        await letters_of_credit.destroy({
            transaction
        });

        return letters_of_credit;
    }

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

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

        if (!letters_of_credit) {
            return letters_of_credit;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.business = await letters_of_credit.getBusiness({
            transaction
        });
        
        
        output.bank = await letters_of_credit.getBank({
            transaction
        });
        
        
        output.counterparty = await letters_of_credit.getCounterparty({
            transaction
        });
        
        
        output.currency = await letters_of_credit.getCurrency({
            transaction
        });
        
        
        output.attachments = await letters_of_credit.getAttachments({
            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.businesses,
        as: 'business',
        
        where: filter.business ? {
          [Op.or]: [
            { id: { [Op.in]: filter.business.split('|').map(term => Utils.uuid(term)) } },
            {
              trade_name: {
                [Op.or]: filter.business.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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

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



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

    ];

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

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

            
            

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    amount: {
                    ...where.amount,
                            [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.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.letters_of_credit.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(
                        'letters_of_credit',
                        'lc_number',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

