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

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

        const plots = await db.plots.create(
            {
                id: data.id || undefined,
        
        plot_code: data.plot_code
        ||
        null
            ,
            
        row_number: data.row_number
        ||
        null
            ,
            
        column_number: data.column_number
        ||
        null
            ,
            
        area_sq_m: data.area_sq_m
        ||
        null
            ,
            
        target_plant_count: data.target_plant_count
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await plots.setTrial_site( data.trial_site || null, {
            transaction,
        });
        
        await plots.setTrial_entry( data.trial_entry || null, {
            transaction,
        });
        
        await plots.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return 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 plotsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                plot_code: item.plot_code
            ||
            null
            ,
            
                row_number: item.row_number
            ||
            null
            ,
            
                column_number: item.column_number
            ||
            null
            ,
            
                area_sq_m: item.area_sq_m
            ||
            null
            ,
            
                target_plant_count: item.target_plant_count
            ||
            null
            ,
            
                notes: item.notes
            ||
            null
            ,
            
                is_active: item.is_active
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return plots;
    }

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

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


        

        const updatePayload = {};
        
        if (data.plot_code !== undefined) updatePayload.plot_code = data.plot_code;
        
        
        if (data.row_number !== undefined) updatePayload.row_number = data.row_number;
        
        
        if (data.column_number !== undefined) updatePayload.column_number = data.column_number;
        
        
        if (data.area_sq_m !== undefined) updatePayload.area_sq_m = data.area_sq_m;
        
        
        if (data.target_plant_count !== undefined) updatePayload.target_plant_count = data.target_plant_count;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.trial_site !== undefined) {
            await plots.setTrial_site(
              
              data.trial_site,
              
              { transaction }
            );
        }
        
        if (data.trial_entry !== undefined) {
            await plots.setTrial_entry(
              
              data.trial_entry,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await plots.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return plots;
    }

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

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

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


        return plots;
    }

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

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

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

        await plots.destroy({
            transaction
        });

        return plots;
    }

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

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

        if (!plots) {
            return plots;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        output.plants_plot = await plots.getPlants_plot({
            transaction
        });
        
        
        output.observation_events_plot = await plots.getObservation_events_plot({
            transaction
        });
        
        
        
        
        
        
        
        
        
        output.trial_site = await plots.getTrial_site({
            transaction
        });
        
        
        output.trial_entry = await plots.getTrial_entry({
            transaction
        });
        
        
        output.organizations = await plots.getOrganizations({
            transaction
        });
        
        

        return output;
    }

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

        
        const user = (options && options.currentUser) || null;
        const userOrganizations = (user && user.organizations?.id) || null;
        

        
        if (userOrganizations) {
            if (options?.currentUser?.organizationsId) {
                where.organizationsId = options.currentUser.organizationsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

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

    let include = [

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

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

      {
        model: db.organizations,
        as: 'organizations',
        
      },



    ];

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

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

            
            

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

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

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

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

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

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

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

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

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

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

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


      

      

      
      if (filter.organizations) {
        const listItems = filter.organizations.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          organizationsId: {[Op.or]: listItems}
        };
      }
      



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

        
        if (globalAccess) {
            delete where.organizationsId;
        }
        

        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.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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

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

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

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

    
};

