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

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

        const farm_plots = await db.farm_plots.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        width_tiles: data.width_tiles
        ||
        null
            ,
            
        height_tiles: data.height_tiles
        ||
        null
            ,
            
        is_irrigated: data.is_irrigated
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await farm_plots.setOwner_profile( data.owner_profile || null, {
            transaction,
        });
        
        await farm_plots.setLocation( data.location || null, {
            transaction,
        });
        

        

        

        return farm_plots;
    }
    

    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 farm_plotsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                width_tiles: item.width_tiles
            ||
            null
            ,
            
                height_tiles: item.height_tiles
            ||
            null
            ,
            
                is_irrigated: item.is_irrigated
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return farm_plots;
    }

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

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.width_tiles !== undefined) updatePayload.width_tiles = data.width_tiles;
        
        
        if (data.height_tiles !== undefined) updatePayload.height_tiles = data.height_tiles;
        
        
        if (data.is_irrigated !== undefined) updatePayload.is_irrigated = data.is_irrigated;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.owner_profile !== undefined) {
            await farm_plots.setOwner_profile(
              
              data.owner_profile,
              
              { transaction }
            );
        }
        
        if (data.location !== undefined) {
            await farm_plots.setLocation(
              
              data.location,
              
              { transaction }
            );
        }
        

        
        

        

        return farm_plots;
    }

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

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

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


        return farm_plots;
    }

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

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

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

        await farm_plots.destroy({
            transaction
        });

        return farm_plots;
    }

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

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

        if (!farm_plots) {
            return farm_plots;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.plantings_farm_plot = await farm_plots.getPlantings_farm_plot({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.owner_profile = await farm_plots.getOwner_profile({
            transaction
        });
        
        
        output.location = await farm_plots.getLocation({
            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.player_profiles,
        as: 'owner_profile',
        
        where: filter.owner_profile ? {
          [Op.or]: [
            { id: { [Op.in]: filter.owner_profile.split('|').map(term => Utils.uuid(term)) } },
            {
              first_name: {
                [Op.or]: filter.owner_profile.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

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

            
            

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

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

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

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

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

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

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


      

      



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

        const records = await db.farm_plots.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,
        }));
    }

    
};

