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

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

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

        
        await customer_returns.setTenant( data.tenant || null, {
            transaction,
        });
        
        await customer_returns.setCustomer( data.customer || null, {
            transaction,
        });
        
        await customer_returns.setInvoice( data.invoice || null, {
            transaction,
        });
        
        await customer_returns.setSales_order( data.sales_order || null, {
            transaction,
        });
        
        await customer_returns.setOrganizations( data.organizations || null, {
            transaction,
        });
        

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

        

        return customer_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 customer_returnsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                return_number: item.return_number
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                requested_at: item.requested_at
            ||
            null
            ,
            
                received_at: item.received_at
            ||
            null
            ,
            
                reason: item.reason
            ||
            null
            ,
            
                refund_total: item.refund_total
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

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


        

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

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

        
        
        if (data.tenant !== undefined) {
            await customer_returns.setTenant(
              
              data.tenant,
              
              { transaction }
            );
        }
        
        if (data.customer !== undefined) {
            await customer_returns.setCustomer(
              
              data.customer,
              
              { transaction }
            );
        }
        
        if (data.invoice !== undefined) {
            await customer_returns.setInvoice(
              
              data.invoice,
              
              { transaction }
            );
        }
        
        if (data.sales_order !== undefined) {
            await customer_returns.setSales_order(
              
              data.sales_order,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await customer_returns.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

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

        

        return customer_returns;
    }

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

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

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


        return customer_returns;
    }

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

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

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

        await customer_returns.destroy({
            transaction
        });

        return customer_returns;
    }

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

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

        if (!customer_returns) {
            return customer_returns;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.customer_return_lines_customer_return = await customer_returns.getCustomer_return_lines_customer_return({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.tenant = await customer_returns.getTenant({
            transaction
        });
        
        
        output.customer = await customer_returns.getCustomer({
            transaction
        });
        
        
        output.invoice = await customer_returns.getInvoice({
            transaction
        });
        
        
        output.sales_order = await customer_returns.getSales_order({
            transaction
        });
        
        
        output.lines = await customer_returns.getLines({
            transaction
        });
        
        
        output.organizations = await customer_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.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.customers,
        as: 'customer',
        
        where: filter.customer ? {
          [Op.or]: [
            { id: { [Op.in]: filter.customer.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.customer.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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

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


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


    ];

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

            
            if (filter.return_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'customer_returns',
                        'return_number',
                        filter.return_number,
                    ),
                };
            }
            
            if (filter.reason) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'customer_returns',
                        'reason',
                        filter.reason,
                    ),
                };
            }
            

            
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    requested_at: {
                    ...where.requested_at,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            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.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.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.customer_return_lines,
            as: 'lines_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  condition_notes: {
                    [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.customer_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(
                        'customer_returns',
                        'return_number',
                        query,
                    ),
                ],
            };
        }

        const records = await db.customer_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,
        }));
    }

    
};

