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

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

        const crops = await db.crops.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        growth_days: data.growth_days
        ||
        null
            ,
            
        regrowth_days: data.regrowth_days
        ||
        null
            ,
            
        is_perennial: data.is_perennial
        ||
        false
        
            ,
            
        preferred_season: data.preferred_season
        ||
        null
            ,
            
        water_per_day: data.water_per_day
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await crops.setSeed_item( data.seed_item || null, {
            transaction,
        });
        
        await crops.setHarvest_item( data.harvest_item || null, {
            transaction,
        });
        

        

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

        return crops;
    }
    

    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 cropsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                growth_days: item.growth_days
            ||
            null
            ,
            
                regrowth_days: item.regrowth_days
            ||
            null
            ,
            
                is_perennial: item.is_perennial
            ||
            false
        
            ,
            
                preferred_season: item.preferred_season
            ||
            null
            ,
            
                water_per_day: item.water_per_day
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return crops;
    }

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

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.growth_days !== undefined) updatePayload.growth_days = data.growth_days;
        
        
        if (data.regrowth_days !== undefined) updatePayload.regrowth_days = data.regrowth_days;
        
        
        if (data.is_perennial !== undefined) updatePayload.is_perennial = data.is_perennial;
        
        
        if (data.preferred_season !== undefined) updatePayload.preferred_season = data.preferred_season;
        
        
        if (data.water_per_day !== undefined) updatePayload.water_per_day = data.water_per_day;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.seed_item !== undefined) {
            await crops.setSeed_item(
              
              data.seed_item,
              
              { transaction }
            );
        }
        
        if (data.harvest_item !== undefined) {
            await crops.setHarvest_item(
              
              data.harvest_item,
              
              { transaction }
            );
        }
        

        
        

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

        return crops;
    }

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

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

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


        return crops;
    }

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

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

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

        await crops.destroy({
            transaction
        });

        return crops;
    }

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

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

        if (!crops) {
            return crops;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.plantings_crop = await crops.getPlantings_crop({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.seed_item = await crops.getSeed_item({
            transaction
        });
        
        
        output.harvest_item = await crops.getHarvest_item({
            transaction
        });
        
        
        output.crop_images = await crops.getCrop_images({
            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.items,
        as: 'seed_item',
        
        where: filter.seed_item ? {
          [Op.or]: [
            { id: { [Op.in]: filter.seed_item.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.seed_item.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



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

    ];

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

            
            if (filter.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'crops',
                        'name',
                        filter.name,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

            
            if (filter.is_perennial) {
                where = {
                    ...where,
                is_perennial: filter.is_perennial,
            };
            }
            
            if (filter.preferred_season) {
                where = {
                    ...where,
                preferred_season: filter.preferred_season,
            };
            }
            


      

      



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

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

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

    
};

