
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
            ,
            
        received_at: data.received_at
        ||
        null
            ,
            
        receipt_status: data.receipt_status
        ||
        null
            ,
            
        supplier_document_ref: data.supplier_document_ref
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await receipts.setSupplier( data.supplier || null, {
            transaction,
        });
        
        await receipts.setReceived_by( data.received_by || null, {
            transaction,
        });
        
        await receipts.setTo_location( data.to_location || 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
            ,
            
                received_at: item.received_at
            ||
            null
            ,
            
                receipt_status: item.receipt_status
            ||
            null
            ,
            
                supplier_document_ref: item.supplier_document_ref
            ||
            null
            ,
            
                notes: item.notes
            ||
            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.received_at !== undefined) updatePayload.received_at = data.received_at;
        
        
        if (data.receipt_status !== undefined) updatePayload.receipt_status = data.receipt_status;
        
        
        if (data.supplier_document_ref !== undefined) updatePayload.supplier_document_ref = data.supplier_document_ref;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.supplier !== undefined) {
            await receipts.setSupplier(
              
              data.supplier,
              
              { transaction }
            );
        }
        
        if (data.received_by !== undefined) {
            await receipts.setReceived_by(
              
              data.received_by,
              
              { transaction }
            );
        }
        
        if (data.to_location !== undefined) {
            await receipts.setTo_location(
              
              data.to_location,
              
              { 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.supplier = await receipts.getSupplier({
            transaction
        });
        
        
        output.received_by = await receipts.getReceived_by({
            transaction
        });
        
        
        output.to_location = await receipts.getTo_location({
            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.suppliers,
        as: 'supplier',
        
        where: filter.supplier ? {
          [Op.or]: [
            { id: { [Op.in]: filter.supplier.split('|').map(term => Utils.uuid(term)) } },
            {
              supplier_name: {
                [Op.or]: filter.supplier.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.locations,
        as: 'to_location',
        
        where: filter.to_location ? {
          [Op.or]: [
            { id: { [Op.in]: filter.to_location.split('|').map(term => Utils.uuid(term)) } },
            {
              location_name: {
                [Op.or]: filter.to_location.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.supplier_document_ref) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'receipts',
                        'supplier_document_ref',
                        filter.supplier_document_ref,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'receipts',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

            
            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.receipt_status) {
                where = {
                    ...where,
                receipt_status: filter.receipt_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,
        }));
    }

    
};

