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

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

        const returns = await db.returns.create(
            {
                id: data.id || undefined,
        
        return_number: data.return_number
        ||
        null
            ,
            
        returned_at: data.returned_at
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        reason: data.reason
        ||
        null
            ,
            
        refund_total: data.refund_total
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await returns.setOriginal_sale( data.original_sale || null, {
            transaction,
        });
        
        await returns.setStore( data.store || null, {
            transaction,
        });
        
        await returns.setProcessed_by_user( data.processed_by_user || null, {
            transaction,
        });
        
        await returns.setCustomer( data.customer || null, {
            transaction,
        });
        
        await returns.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return returns;
    }
    

    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 returnsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                return_number: item.return_number
            ||
            null
            ,
            
                returned_at: item.returned_at
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                reason: item.reason
            ||
            null
            ,
            
                refund_total: item.refund_total
            ||
            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 returns = await db.returns.bulkCreate(returnsData, { transaction });

        // For each item created, replace relation files
        

        return returns;
    }

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


        

        const updatePayload = {};
        
        if (data.return_number !== undefined) updatePayload.return_number = data.return_number;
        
        
        if (data.returned_at !== undefined) updatePayload.returned_at = data.returned_at;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.reason !== undefined) updatePayload.reason = data.reason;
        
        
        if (data.refund_total !== undefined) updatePayload.refund_total = data.refund_total;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.original_sale !== undefined) {
            await returns.setOriginal_sale(
              
              data.original_sale,
              
              { transaction }
            );
        }
        
        if (data.store !== undefined) {
            await returns.setStore(
              
              data.store,
              
              { transaction }
            );
        }
        
        if (data.processed_by_user !== undefined) {
            await returns.setProcessed_by_user(
              
              data.processed_by_user,
              
              { transaction }
            );
        }
        
        if (data.customer !== undefined) {
            await returns.setCustomer(
              
              data.customer,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await returns.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return returns;
    }

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

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

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


        return returns;
    }

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

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

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

        await returns.destroy({
            transaction
        });

        return returns;
    }

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

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

        if (!returns) {
            return returns;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.return_items_return = await returns.getReturn_items_return({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        output.original_sale = await returns.getOriginal_sale({
            transaction
        });
        
        
        output.store = await returns.getStore({
            transaction
        });
        
        
        output.processed_by_user = await returns.getProcessed_by_user({
            transaction
        });
        
        
        output.customer = await returns.getCustomer({
            transaction
        });
        
        
        output.organizations = await returns.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.sales,
        as: 'original_sale',
        
        where: filter.original_sale ? {
          [Op.or]: [
            { id: { [Op.in]: filter.original_sale.split('|').map(term => Utils.uuid(term)) } },
            {
              receipt_number: {
                [Op.or]: filter.original_sale.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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

      {
        model: db.customers,
        as: 'customer',
        
        where: filter.customer ? {
          [Op.or]: [
            { id: { [Op.in]: filter.customer.split('|').map(term => Utils.uuid(term)) } },
            {
              full_name: {
                [Op.or]: filter.customer.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.return_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'returns',
                        'return_number',
                        filter.return_number,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'returns',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    refund_total: {
                    ...where.refund_total,
                            [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.reason) {
                where = {
                    ...where,
                reason: filter.reason,
            };
            }
            


      

      

      

      

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

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

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

    
};

