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

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

        const receipts = await db.receipts.create(
            {
                id: data.id || undefined,
        
        receipt_number: data.receipt_number
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        received_at: data.received_at
        ||
        null
            ,
            
        carrier_reference: data.carrier_reference
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await receipts.setPurchase_order( data.purchase_order || null, {
            transaction,
        });
        
        await receipts.setWarehouse( data.warehouse || null, {
            transaction,
        });
        
        await receipts.setReceived_by( data.received_by || null, {
            transaction,
        });
        

        

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

        return receipts;
    }
    

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

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

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

        return receipts;
    }

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

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


        

        const updatePayload = {};
        
        if (data.receipt_number !== undefined) updatePayload.receipt_number = data.receipt_number;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.received_at !== undefined) updatePayload.received_at = data.received_at;
        
        
        if (data.carrier_reference !== undefined) updatePayload.carrier_reference = data.carrier_reference;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.purchase_order !== undefined) {
            await receipts.setPurchase_order(
              
              data.purchase_order,
              
              { transaction }
            );
        }
        
        if (data.warehouse !== undefined) {
            await receipts.setWarehouse(
              
              data.warehouse,
              
              { transaction }
            );
        }
        
        if (data.received_by !== undefined) {
            await receipts.setReceived_by(
              
              data.received_by,
              
              { transaction }
            );
        }
        

        
        

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

        return receipts;
    }

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

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

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


        return receipts;
    }

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

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

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

        await receipts.destroy({
            transaction
        });

        return receipts;
    }

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

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

        if (!receipts) {
            return receipts;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.receipt_lines_receipt = await receipts.getReceipt_lines_receipt({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.purchase_order = await receipts.getPurchase_order({
            transaction
        });
        
        
        output.warehouse = await receipts.getWarehouse({
            transaction
        });
        
        
        output.received_by = await receipts.getReceived_by({
            transaction
        });
        
        
        output.attachments = await receipts.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.purchase_orders,
        as: 'purchase_order',
        
        where: filter.purchase_order ? {
          [Op.or]: [
            { id: { [Op.in]: filter.purchase_order.split('|').map(term => Utils.uuid(term)) } },
            {
              po_number: {
                [Op.or]: filter.purchase_order.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

      {
        model: db.users,
        as: 'received_by',
        
        where: filter.received_by ? {
          [Op.or]: [
            { id: { [Op.in]: filter.received_by.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.received_by.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.receipt_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'receipts',
                        'receipt_number',
                        filter.receipt_number,
                    ),
                };
            }
            
            if (filter.carrier_reference) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'receipts',
                        'carrier_reference',
                        filter.carrier_reference,
                    ),
                };
            }
            

            
            

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

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

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

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

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

    
};

