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

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

        const treatments = await db.treatments.create(
            {
                id: data.id || undefined,
        
        treatment_type: data.treatment_type
        ||
        null
            ,
            
        product_name: data.product_name
        ||
        null
            ,
            
        dosage: data.dosage
        ||
        null
            ,
            
        administered_at: data.administered_at
        ||
        null
            ,
            
        next_due_at: data.next_due_at
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await treatments.setPoultry_lot( data.poultry_lot || null, {
            transaction,
        });
        
        await treatments.setPerformed_by_user( data.performed_by_user || null, {
            transaction,
        });
        

        

        

        return treatments;
    }
    

    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 treatmentsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                treatment_type: item.treatment_type
            ||
            null
            ,
            
                product_name: item.product_name
            ||
            null
            ,
            
                dosage: item.dosage
            ||
            null
            ,
            
                administered_at: item.administered_at
            ||
            null
            ,
            
                next_due_at: item.next_due_at
            ||
            null
            ,
            
                status: item.status
            ||
            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 treatments = await db.treatments.bulkCreate(treatmentsData, { transaction });

        // For each item created, replace relation files
        

        return treatments;
    }

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

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


        

        const updatePayload = {};
        
        if (data.treatment_type !== undefined) updatePayload.treatment_type = data.treatment_type;
        
        
        if (data.product_name !== undefined) updatePayload.product_name = data.product_name;
        
        
        if (data.dosage !== undefined) updatePayload.dosage = data.dosage;
        
        
        if (data.administered_at !== undefined) updatePayload.administered_at = data.administered_at;
        
        
        if (data.next_due_at !== undefined) updatePayload.next_due_at = data.next_due_at;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.poultry_lot !== undefined) {
            await treatments.setPoultry_lot(
              
              data.poultry_lot,
              
              { transaction }
            );
        }
        
        if (data.performed_by_user !== undefined) {
            await treatments.setPerformed_by_user(
              
              data.performed_by_user,
              
              { transaction }
            );
        }
        

        
        

        

        return treatments;
    }

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

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

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


        return treatments;
    }

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

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

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

        await treatments.destroy({
            transaction
        });

        return treatments;
    }

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

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

        if (!treatments) {
            return treatments;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.poultry_lot = await treatments.getPoultry_lot({
            transaction
        });
        
        
        output.performed_by_user = await treatments.getPerformed_by_user({
            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.poultry_lots,
        as: 'poultry_lot',
        
        where: filter.poultry_lot ? {
          [Op.or]: [
            { id: { [Op.in]: filter.poultry_lot.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.poultry_lot.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

            
            if (filter.product_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'treatments',
                        'product_name',
                        filter.product_name,
                    ),
                };
            }
            
            if (filter.dosage) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'treatments',
                        'dosage',
                        filter.dosage,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'treatments',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

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

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

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

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

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

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

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

            
            if (filter.treatment_type) {
                where = {
                    ...where,
                treatment_type: filter.treatment_type,
            };
            }
            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            


      

      



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

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

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

    
};

