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

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

        const plantings = await db.plantings.create(
            {
                id: data.id || undefined,
        
        planted_at: data.planted_at
        ||
        null
            ,
            
        estimated_harvest_at: data.estimated_harvest_at
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        quantity_planted: data.quantity_planted
        ||
        null
            ,
            
        watered_today: data.watered_today
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await plantings.setFarm_plot( data.farm_plot || null, {
            transaction,
        });
        
        await plantings.setCrop( data.crop || null, {
            transaction,
        });
        

        

        

        return plantings;
    }
    

    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 plantingsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                planted_at: item.planted_at
            ||
            null
            ,
            
                estimated_harvest_at: item.estimated_harvest_at
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                quantity_planted: item.quantity_planted
            ||
            null
            ,
            
                watered_today: item.watered_today
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return plantings;
    }

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

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


        

        const updatePayload = {};
        
        if (data.planted_at !== undefined) updatePayload.planted_at = data.planted_at;
        
        
        if (data.estimated_harvest_at !== undefined) updatePayload.estimated_harvest_at = data.estimated_harvest_at;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.quantity_planted !== undefined) updatePayload.quantity_planted = data.quantity_planted;
        
        
        if (data.watered_today !== undefined) updatePayload.watered_today = data.watered_today;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.farm_plot !== undefined) {
            await plantings.setFarm_plot(
              
              data.farm_plot,
              
              { transaction }
            );
        }
        
        if (data.crop !== undefined) {
            await plantings.setCrop(
              
              data.crop,
              
              { transaction }
            );
        }
        

        
        

        

        return plantings;
    }

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

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

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


        return plantings;
    }

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

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

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

        await plantings.destroy({
            transaction
        });

        return plantings;
    }

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

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

        if (!plantings) {
            return plantings;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.farm_plot = await plantings.getFarm_plot({
            transaction
        });
        
        
        output.crop = await plantings.getCrop({
            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.farm_plots,
        as: 'farm_plot',
        
        where: filter.farm_plot ? {
          [Op.or]: [
            { id: { [Op.in]: filter.farm_plot.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.farm_plot.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

            

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

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

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

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    watered_today: {
                    ...where.watered_today,
                            [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.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.plantings.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(
                        'plantings',
                        'status',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

