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

        
        await receipts.setTenant( data.tenant || null, {
            transaction,
        });
        
        await receipts.setPurchase_order( data.purchase_order || null, {
            transaction,
        });
        
        await receipts.setReceived_into_location( data.received_into_location || null, {
            transaction,
        });
        
        await receipts.setReceived_by( data.received_by || null, {
            transaction,
        });
        
        await receipts.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        
        await receipts.setLines(data.lines || [], {
            transaction,
        });
        

        

        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
            ,
            
                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
        

        return receipts;
    }

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

        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.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.tenant !== undefined) {
            await receipts.setTenant(
              
              data.tenant,
              
              { transaction }
            );
        }
        
        if (data.purchase_order !== undefined) {
            await receipts.setPurchase_order(
              
              data.purchase_order,
              
              { transaction }
            );
        }
        
        if (data.received_into_location !== undefined) {
            await receipts.setReceived_into_location(
              
              data.received_into_location,
              
              { transaction }
            );
        }
        
        if (data.received_by !== undefined) {
            await receipts.setReceived_by(
              
              data.received_by,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await receipts.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        
        if (data.lines !== undefined) {
            await receipts.setLines(data.lines, { transaction });
        }
        

        

        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.tenant = await receipts.getTenant({
            transaction
        });
        
        
        output.purchase_order = await receipts.getPurchase_order({
            transaction
        });
        
        
        output.received_into_location = await receipts.getReceived_into_location({
            transaction
        });
        
        
        output.received_by = await receipts.getReceived_by({
            transaction
        });
        
        
        output.lines = await receipts.getLines({
            transaction
        });
        
        
        output.organizations = await receipts.getOrganizations({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           globalAccess,  options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        
        const user = (options && options.currentUser) || null;
        const userOrganizations = (user && user.organizations?.id) || null;
        

        
        if (userOrganizations) {
            if (options?.currentUser?.organizationsId) {
                where.organizationsId = options.currentUser.organizationsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

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

      {
        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.locations,
        as: 'received_into_location',
        
        where: filter.received_into_location ? {
          [Op.or]: [
            { id: { [Op.in]: filter.received_into_location.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.received_into_location.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.organizations,
        as: 'organizations',
        
      },


      {
        model: db.receipt_lines,
        as: 'lines',
        required: false,
      },


    ];

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


      

      

      

      

      
      if (filter.organizations) {
        const listItems = filter.organizations.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          organizationsId: {[Op.or]: listItems}
        };
      }
      


      if (filter.lines) {
        const searchTerms = filter.lines.split('|');

        include = [
          {
            model: db.receipt_lines,
            as: 'lines_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  memo: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }


            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,
                        },
                    };
                }
            }
        }
        

        
        if (globalAccess) {
            delete where.organizationsId;
        }
        

        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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

        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,
        }));
    }

    
};

