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

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

        const purchase_requisitions = await db.purchase_requisitions.create(
            {
                id: data.id || undefined,
        
        requisition_number: data.requisition_number
        ||
        null
            ,
            
        requested_date: data.requested_date
        ||
        null
            ,
            
        needed_by: data.needed_by
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        reason: data.reason
        ||
        null
            ,
            
        estimated_total: data.estimated_total
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await purchase_requisitions.setCompany( data.company || null, {
            transaction,
        });
        
        await purchase_requisitions.setRequested_by( data.requested_by || null, {
            transaction,
        });
        
        await purchase_requisitions.setDepartment( data.department || null, {
            transaction,
        });
        
        await purchase_requisitions.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

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

        return purchase_requisitions;
    }
    

    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 purchase_requisitionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                requisition_number: item.requisition_number
            ||
            null
            ,
            
                requested_date: item.requested_date
            ||
            null
            ,
            
                needed_by: item.needed_by
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                reason: item.reason
            ||
            null
            ,
            
                estimated_total: item.estimated_total
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return purchase_requisitions;
    }

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


        

        const updatePayload = {};
        
        if (data.requisition_number !== undefined) updatePayload.requisition_number = data.requisition_number;
        
        
        if (data.requested_date !== undefined) updatePayload.requested_date = data.requested_date;
        
        
        if (data.needed_by !== undefined) updatePayload.needed_by = data.needed_by;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.reason !== undefined) updatePayload.reason = data.reason;
        
        
        if (data.estimated_total !== undefined) updatePayload.estimated_total = data.estimated_total;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.company !== undefined) {
            await purchase_requisitions.setCompany(
              
              data.company,
              
              { transaction }
            );
        }
        
        if (data.requested_by !== undefined) {
            await purchase_requisitions.setRequested_by(
              
              data.requested_by,
              
              { transaction }
            );
        }
        
        if (data.department !== undefined) {
            await purchase_requisitions.setDepartment(
              
              data.department,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await purchase_requisitions.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

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

        return purchase_requisitions;
    }

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

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

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


        return purchase_requisitions;
    }

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

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

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

        await purchase_requisitions.destroy({
            transaction
        });

        return purchase_requisitions;
    }

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

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

        if (!purchase_requisitions) {
            return purchase_requisitions;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        output.purchase_requisition_lines_purchase_requisition = await purchase_requisitions.getPurchase_requisition_lines_purchase_requisition({
            transaction
        });
        
        
        output.purchase_orders_source_requisition = await purchase_requisitions.getPurchase_orders_source_requisition({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.company = await purchase_requisitions.getCompany({
            transaction
        });
        
        
        output.requested_by = await purchase_requisitions.getRequested_by({
            transaction
        });
        
        
        output.department = await purchase_requisitions.getDepartment({
            transaction
        });
        
        
        output.attachments = await purchase_requisitions.getAttachments({
            transaction
        });
        
        
        output.organizations = await purchase_requisitions.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.companies,
        as: 'company',
        
        where: filter.company ? {
          [Op.or]: [
            { id: { [Op.in]: filter.company.split('|').map(term => Utils.uuid(term)) } },
            {
              company_name: {
                [Op.or]: filter.company.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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

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



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

    ];

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

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

            
            

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    estimated_total: {
                    ...where.estimated_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.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.purchase_requisitions.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(
                        'purchase_requisitions',
                        'requisition_number',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

