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

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

        const water_quality_logs = await db.water_quality_logs.create(
            {
                id: data.id || undefined,
        
        sampled_at: data.sampled_at
        ||
        null
            ,
            
        temperature_c: data.temperature_c
        ||
        null
            ,
            
        ph: data.ph
        ||
        null
            ,
            
        dissolved_oxygen_mg_l: data.dissolved_oxygen_mg_l
        ||
        null
            ,
            
        salinity_ppt: data.salinity_ppt
        ||
        null
            ,
            
        ammonia_mg_l: data.ammonia_mg_l
        ||
        null
            ,
            
        nitrite_mg_l: data.nitrite_mg_l
        ||
        null
            ,
            
        nitrate_mg_l: data.nitrate_mg_l
        ||
        null
            ,
            
        turbidity_ntu: data.turbidity_ntu
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await water_quality_logs.setTenant( data.tenant || null, {
            transaction,
        });
        
        await water_quality_logs.setPond( data.pond || null, {
            transaction,
        });
        
        await water_quality_logs.setRecorded_by( data.recorded_by || null, {
            transaction,
        });
        
        await water_quality_logs.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return water_quality_logs;
    }
    

    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 water_quality_logsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                sampled_at: item.sampled_at
            ||
            null
            ,
            
                temperature_c: item.temperature_c
            ||
            null
            ,
            
                ph: item.ph
            ||
            null
            ,
            
                dissolved_oxygen_mg_l: item.dissolved_oxygen_mg_l
            ||
            null
            ,
            
                salinity_ppt: item.salinity_ppt
            ||
            null
            ,
            
                ammonia_mg_l: item.ammonia_mg_l
            ||
            null
            ,
            
                nitrite_mg_l: item.nitrite_mg_l
            ||
            null
            ,
            
                nitrate_mg_l: item.nitrate_mg_l
            ||
            null
            ,
            
                turbidity_ntu: item.turbidity_ntu
            ||
            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 water_quality_logs = await db.water_quality_logs.bulkCreate(water_quality_logsData, { transaction });

        // For each item created, replace relation files
        

        return water_quality_logs;
    }

    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 water_quality_logs = await db.water_quality_logs.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.sampled_at !== undefined) updatePayload.sampled_at = data.sampled_at;
        
        
        if (data.temperature_c !== undefined) updatePayload.temperature_c = data.temperature_c;
        
        
        if (data.ph !== undefined) updatePayload.ph = data.ph;
        
        
        if (data.dissolved_oxygen_mg_l !== undefined) updatePayload.dissolved_oxygen_mg_l = data.dissolved_oxygen_mg_l;
        
        
        if (data.salinity_ppt !== undefined) updatePayload.salinity_ppt = data.salinity_ppt;
        
        
        if (data.ammonia_mg_l !== undefined) updatePayload.ammonia_mg_l = data.ammonia_mg_l;
        
        
        if (data.nitrite_mg_l !== undefined) updatePayload.nitrite_mg_l = data.nitrite_mg_l;
        
        
        if (data.nitrate_mg_l !== undefined) updatePayload.nitrate_mg_l = data.nitrate_mg_l;
        
        
        if (data.turbidity_ntu !== undefined) updatePayload.turbidity_ntu = data.turbidity_ntu;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.tenant !== undefined) {
            await water_quality_logs.setTenant(
              
              data.tenant,
              
              { transaction }
            );
        }
        
        if (data.pond !== undefined) {
            await water_quality_logs.setPond(
              
              data.pond,
              
              { transaction }
            );
        }
        
        if (data.recorded_by !== undefined) {
            await water_quality_logs.setRecorded_by(
              
              data.recorded_by,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await water_quality_logs.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return water_quality_logs;
    }

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

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

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


        return water_quality_logs;
    }

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

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

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

        await water_quality_logs.destroy({
            transaction
        });

        return water_quality_logs;
    }

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

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

        if (!water_quality_logs) {
            return water_quality_logs;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.tenant = await water_quality_logs.getTenant({
            transaction
        });
        
        
        output.pond = await water_quality_logs.getPond({
            transaction
        });
        
        
        output.recorded_by = await water_quality_logs.getRecorded_by({
            transaction
        });
        
        
        output.organizations = await water_quality_logs.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.tenants,
        as: 'tenant',
        
        where: filter.tenant ? {
          [Op.or]: [
            { id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
            {
              tenant_name: {
                [Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

      {
        model: db.users,
        as: 'recorded_by',
        
        where: filter.recorded_by ? {
          [Op.or]: [
            { id: { [Op.in]: filter.recorded_by.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.recorded_by.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.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'water_quality_logs',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            


      

      

      

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

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

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

    
};

