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

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

        const purchases = await db.purchases.create(
            {
                id: data.id || undefined,
        
        purchase_number: data.purchase_number
        ||
        null
            ,
            
        items: data.items
        ||
        null
            ,
            
        total: data.total
        ||
        null
            ,
            
        date: data.date
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await purchases.setSupplier( data.supplier || null, {
            transaction,
        });
        

        

        

        return purchases;
    }
    

    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 purchasesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                purchase_number: item.purchase_number
            ||
            null
            ,
            
                items: item.items
            ||
            null
            ,
            
                total: item.total
            ||
            null
            ,
            
                date: item.date
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return purchases;
    }

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

        const purchases = await db.purchases.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.purchase_number !== undefined) updatePayload.purchase_number = data.purchase_number;
        
        
        if (data.items !== undefined) updatePayload.items = data.items;
        
        
        if (data.total !== undefined) updatePayload.total = data.total;
        
        
        if (data.date !== undefined) updatePayload.date = data.date;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.supplier !== undefined) {
            await purchases.setSupplier(
              
              data.supplier,
              
              { transaction }
            );
        }
        

        
        

        

        return purchases;
    }

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

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

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


        return purchases;
    }

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

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

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

        await purchases.destroy({
            transaction
        });

        return purchases;
    }

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

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

        if (!purchases) {
            return purchases;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.supplier = await purchases.getSupplier({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        

        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

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



    ];

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

            
            if (filter.purchase_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'purchases',
                        'purchase_number',
                        filter.purchase_number,
                    ),
                };
            }
            
            if (filter.items) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'purchases',
                        'items',
                        filter.items,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

            


      



            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,
                        },
                    };
                }
            }
        }
        

        

        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.purchases.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, ) {
        let where = {};
        
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'purchases',
                        'purchase_number',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

