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

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

        const customer_return_lines = await db.customer_return_lines.create(
            {
                id: data.id || undefined,
        
        quantity: data.quantity
        ||
        null
            ,
            
        refund_amount: data.refund_amount
        ||
        null
            ,
            
        condition_notes: data.condition_notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await customer_return_lines.setCustomer_return( data.customer_return || null, {
            transaction,
        });
        
        await customer_return_lines.setItem( data.item || null, {
            transaction,
        });
        
        await customer_return_lines.setLot( data.lot || null, {
            transaction,
        });
        
        await customer_return_lines.setSerial_number( data.serial_number || null, {
            transaction,
        });
        
        await customer_return_lines.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return customer_return_lines;
    }
    

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

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

        // For each item created, replace relation files
        

        return customer_return_lines;
    }

    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 customer_return_lines = await db.customer_return_lines.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.quantity !== undefined) updatePayload.quantity = data.quantity;
        
        
        if (data.refund_amount !== undefined) updatePayload.refund_amount = data.refund_amount;
        
        
        if (data.condition_notes !== undefined) updatePayload.condition_notes = data.condition_notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.customer_return !== undefined) {
            await customer_return_lines.setCustomer_return(
              
              data.customer_return,
              
              { transaction }
            );
        }
        
        if (data.item !== undefined) {
            await customer_return_lines.setItem(
              
              data.item,
              
              { transaction }
            );
        }
        
        if (data.lot !== undefined) {
            await customer_return_lines.setLot(
              
              data.lot,
              
              { transaction }
            );
        }
        
        if (data.serial_number !== undefined) {
            await customer_return_lines.setSerial_number(
              
              data.serial_number,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await customer_return_lines.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return customer_return_lines;
    }

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

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

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


        return customer_return_lines;
    }

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

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

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

        await customer_return_lines.destroy({
            transaction
        });

        return customer_return_lines;
    }

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

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

        if (!customer_return_lines) {
            return customer_return_lines;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.customer_return = await customer_return_lines.getCustomer_return({
            transaction
        });
        
        
        output.item = await customer_return_lines.getItem({
            transaction
        });
        
        
        output.lot = await customer_return_lines.getLot({
            transaction
        });
        
        
        output.serial_number = await customer_return_lines.getSerial_number({
            transaction
        });
        
        
        output.organizations = await customer_return_lines.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.customer_returns,
        as: 'customer_return',
        
        where: filter.customer_return ? {
          [Op.or]: [
            { id: { [Op.in]: filter.customer_return.split('|').map(term => Utils.uuid(term)) } },
            {
              return_number: {
                [Op.or]: filter.customer_return.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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

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

      {
        model: db.organizations,
        as: 'organizations',
        
      },



    ];

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

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

            
            

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

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

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

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

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

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

            


      

      

      

      

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

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



            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.customer_return_lines.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(
                        'customer_return_lines',
                        'condition_notes',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

