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

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

        const grants = await db.grants.create(
            {
                id: data.id || undefined,
        
        funding_window_name: data.funding_window_name
        ||
        null
            ,
            
        call_reference: data.call_reference
        ||
        null
            ,
            
        call_open_at: data.call_open_at
        ||
        null
            ,
            
        call_close_at: data.call_close_at
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        eligibility_rules: data.eligibility_rules
        ||
        null
            ,
            
        total_envelope_amount: data.total_envelope_amount
        ||
        null
            ,
            
        currency: data.currency
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await grants.setOrganization(currentUser.organization.id || null, {
            transaction,
        });
        
        await grants.setProgram( data.program || null, {
            transaction,
        });
        

        

        

        return grants;
    }
    

    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 grantsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                funding_window_name: item.funding_window_name
            ||
            null
            ,
            
                call_reference: item.call_reference
            ||
            null
            ,
            
                call_open_at: item.call_open_at
            ||
            null
            ,
            
                call_close_at: item.call_close_at
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                eligibility_rules: item.eligibility_rules
            ||
            null
            ,
            
                total_envelope_amount: item.total_envelope_amount
            ||
            null
            ,
            
                currency: item.currency
            ||
            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 grants = await db.grants.bulkCreate(grantsData, { transaction });

        // For each item created, replace relation files
        

        return grants;
    }

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


        

        const updatePayload = {};
        
        if (data.funding_window_name !== undefined) updatePayload.funding_window_name = data.funding_window_name;
        
        
        if (data.call_reference !== undefined) updatePayload.call_reference = data.call_reference;
        
        
        if (data.call_open_at !== undefined) updatePayload.call_open_at = data.call_open_at;
        
        
        if (data.call_close_at !== undefined) updatePayload.call_close_at = data.call_close_at;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.eligibility_rules !== undefined) updatePayload.eligibility_rules = data.eligibility_rules;
        
        
        if (data.total_envelope_amount !== undefined) updatePayload.total_envelope_amount = data.total_envelope_amount;
        
        
        if (data.currency !== undefined) updatePayload.currency = data.currency;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.organization !== undefined) {
            await grants.setOrganization(
              
              (globalAccess ? data.organization : currentUser.organization.id),
              
              { transaction }
            );
        }
        
        if (data.program !== undefined) {
            await grants.setProgram(
              
              data.program,
              
              { transaction }
            );
        }
        

        
        

        

        return grants;
    }

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

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

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


        return grants;
    }

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

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

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

        await grants.destroy({
            transaction
        });

        return grants;
    }

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

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

        if (!grants) {
            return grants;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.beneficiaries_grant = await grants.getBeneficiaries_grant({
            transaction
        });
        
        
        output.grant_applications_grant = await grants.getGrant_applications_grant({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.organization = await grants.getOrganization({
            transaction
        });
        
        
        output.program = await grants.getProgram({
            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.organizations,
        as: 'organization',
        
      },

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



    ];

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

            
            if (filter.funding_window_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'grants',
                        'funding_window_name',
                        filter.funding_window_name,
                    ),
                };
            }
            
            if (filter.call_reference) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'grants',
                        'call_reference',
                        filter.call_reference,
                    ),
                };
            }
            
            if (filter.eligibility_rules) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'grants',
                        'eligibility_rules',
                        filter.eligibility_rules,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'grants',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

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

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    total_envelope_amount: {
                    ...where.total_envelope_amount,
                            [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.currency) {
                where = {
                    ...where,
                currency: filter.currency,
            };
            }
            


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

        where = {
          ...where,
          organizationId: {[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.grants.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(
                        'grants',
                        'call_reference',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

