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

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

        const delivery_notes = await db.delivery_notes.create(
            {
                id: data.id || undefined,
        
        delivery_note_number: data.delivery_note_number
        ||
        null
            ,
            
        issue_date: data.issue_date
        ||
        null
            ,
            
        delivered_at: data.delivered_at
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        carrier_name: data.carrier_name
        ||
        null
            ,
            
        tracking_reference: data.tracking_reference
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await delivery_notes.setOrganization(currentUser.organization.id || null, {
            transaction,
        });
        
        await delivery_notes.setSales_order( data.sales_order || null, {
            transaction,
        });
        
        await delivery_notes.setClient( data.client || null, {
            transaction,
        });
        
        await delivery_notes.setWarehouse( data.warehouse || null, {
            transaction,
        });
        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.delivery_notes.getTableName(),
                belongsToColumn: 'pdf_file',
                belongsToId: delivery_notes.id,
            },
            data.pdf_file,
            options,
        );
        

        return delivery_notes;
    }
    

    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 delivery_notesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                delivery_note_number: item.delivery_note_number
            ||
            null
            ,
            
                issue_date: item.issue_date
            ||
            null
            ,
            
                delivered_at: item.delivered_at
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                carrier_name: item.carrier_name
            ||
            null
            ,
            
                tracking_reference: item.tracking_reference
            ||
            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 delivery_notes = await db.delivery_notes.bulkCreate(delivery_notesData, { transaction });

        // For each item created, replace relation files
        
        for (let i = 0; i < delivery_notes.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.delivery_notes.getTableName(),
                    belongsToColumn: 'pdf_file',
                    belongsToId: delivery_notes[i].id,
                },
                data[i].pdf_file,
                options,
            );
        }
        

        return delivery_notes;
    }

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


        

        const updatePayload = {};
        
        if (data.delivery_note_number !== undefined) updatePayload.delivery_note_number = data.delivery_note_number;
        
        
        if (data.issue_date !== undefined) updatePayload.issue_date = data.issue_date;
        
        
        if (data.delivered_at !== undefined) updatePayload.delivered_at = data.delivered_at;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.carrier_name !== undefined) updatePayload.carrier_name = data.carrier_name;
        
        
        if (data.tracking_reference !== undefined) updatePayload.tracking_reference = data.tracking_reference;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.organization !== undefined) {
            await delivery_notes.setOrganization(
              
              (globalAccess ? data.organization : currentUser.organization.id),
              
              { transaction }
            );
        }
        
        if (data.sales_order !== undefined) {
            await delivery_notes.setSales_order(
              
              data.sales_order,
              
              { transaction }
            );
        }
        
        if (data.client !== undefined) {
            await delivery_notes.setClient(
              
              data.client,
              
              { transaction }
            );
        }
        
        if (data.warehouse !== undefined) {
            await delivery_notes.setWarehouse(
              
              data.warehouse,
              
              { transaction }
            );
        }
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.delivery_notes.getTableName(),
                belongsToColumn: 'pdf_file',
                belongsToId: delivery_notes.id,
            },
            data.pdf_file,
            options,
        );
        

        return delivery_notes;
    }

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

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

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


        return delivery_notes;
    }

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

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

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

        await delivery_notes.destroy({
            transaction
        });

        return delivery_notes;
    }

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

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

        if (!delivery_notes) {
            return delivery_notes;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.delivery_note_items_delivery_note = await delivery_notes.getDelivery_note_items_delivery_note({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.organization = await delivery_notes.getOrganization({
            transaction
        });
        
        
        output.sales_order = await delivery_notes.getSales_order({
            transaction
        });
        
        
        output.client = await delivery_notes.getClient({
            transaction
        });
        
        
        output.warehouse = await delivery_notes.getWarehouse({
            transaction
        });
        
        
        output.pdf_file = await delivery_notes.getPdf_file({
            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.organizations,
        as: 'organization',
        
      },

      {
        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.clients,
        as: 'client',
        
        where: filter.client ? {
          [Op.or]: [
            { id: { [Op.in]: filter.client.split('|').map(term => Utils.uuid(term)) } },
            {
              display_name: {
                [Op.or]: filter.client.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



      {
        model: db.file,
        as: 'pdf_file',
      },

    ];

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

            
            if (filter.delivery_note_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'delivery_notes',
                        'delivery_note_number',
                        filter.delivery_note_number,
                    ),
                };
            }
            
            if (filter.carrier_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'delivery_notes',
                        'carrier_name',
                        filter.carrier_name,
                    ),
                };
            }
            
            if (filter.tracking_reference) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'delivery_notes',
                        'tracking_reference',
                        filter.tracking_reference,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'delivery_notes',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            
            if (filter.calendarStart && filter.calendarEnd) {
                where = {
                    ...where,
                    [Op.or]: [
                        {
                            issue_date: {
                                [Op.between]: [filter.calendarStart, filter.calendarEnd],
                            },
                    },
                {
                    delivered_at: {
                        [Op.between]: [filter.calendarStart, filter.calendarEnd],
                    },
                },
                ],
            };
            }
            

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    delivered_at: {
                    ...where.delivered_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.organization) {
        const listItems = filter.organization.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          organizationId: {[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.delivery_notes.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(
                        'delivery_notes',
                        'delivery_note_number',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

