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

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

        const beneficiaries = await db.beneficiaries.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        beneficiary_type: data.beneficiary_type
        ||
        null
            ,
            
        registration_number: data.registration_number
        ||
        null
            ,
            
        contact_email: data.contact_email
        ||
        null
            ,
            
        contact_phone: data.contact_phone
        ||
        null
            ,
            
        approved_amount: data.approved_amount
        ||
        null
            ,
            
        currency: data.currency
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        approved_at: data.approved_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await beneficiaries.setGrant( data.grant || null, {
            transaction,
        });
        
        await beneficiaries.setProvince( data.province || null, {
            transaction,
        });
        
        await beneficiaries.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return beneficiaries;
    }
    

    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 beneficiariesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                beneficiary_type: item.beneficiary_type
            ||
            null
            ,
            
                registration_number: item.registration_number
            ||
            null
            ,
            
                contact_email: item.contact_email
            ||
            null
            ,
            
                contact_phone: item.contact_phone
            ||
            null
            ,
            
                approved_amount: item.approved_amount
            ||
            null
            ,
            
                currency: item.currency
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                approved_at: item.approved_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return beneficiaries;
    }

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.beneficiary_type !== undefined) updatePayload.beneficiary_type = data.beneficiary_type;
        
        
        if (data.registration_number !== undefined) updatePayload.registration_number = data.registration_number;
        
        
        if (data.contact_email !== undefined) updatePayload.contact_email = data.contact_email;
        
        
        if (data.contact_phone !== undefined) updatePayload.contact_phone = data.contact_phone;
        
        
        if (data.approved_amount !== undefined) updatePayload.approved_amount = data.approved_amount;
        
        
        if (data.currency !== undefined) updatePayload.currency = data.currency;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.approved_at !== undefined) updatePayload.approved_at = data.approved_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.grant !== undefined) {
            await beneficiaries.setGrant(
              
              data.grant,
              
              { transaction }
            );
        }
        
        if (data.province !== undefined) {
            await beneficiaries.setProvince(
              
              data.province,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await beneficiaries.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return beneficiaries;
    }

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

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

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


        return beneficiaries;
    }

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

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

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

        await beneficiaries.destroy({
            transaction
        });

        return beneficiaries;
    }

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

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

        if (!beneficiaries) {
            return beneficiaries;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.grant_applications_beneficiary = await beneficiaries.getGrant_applications_beneficiary({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.grant = await beneficiaries.getGrant({
            transaction
        });
        
        
        output.province = await beneficiaries.getProvince({
            transaction
        });
        
        
        output.organizations = await beneficiaries.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.grants,
        as: 'grant',
        
        where: filter.grant ? {
          [Op.or]: [
            { id: { [Op.in]: filter.grant.split('|').map(term => Utils.uuid(term)) } },
            {
              call_reference: {
                [Op.or]: filter.grant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.provinces,
        as: 'province',
        
        where: filter.province ? {
          [Op.or]: [
            { id: { [Op.in]: filter.province.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.province.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.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'beneficiaries',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.registration_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'beneficiaries',
                        'registration_number',
                        filter.registration_number,
                    ),
                };
            }
            
            if (filter.contact_email) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'beneficiaries',
                        'contact_email',
                        filter.contact_email,
                    ),
                };
            }
            
            if (filter.contact_phone) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'beneficiaries',
                        'contact_phone',
                        filter.contact_phone,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

            
            if (filter.beneficiary_type) {
                where = {
                    ...where,
                beneficiary_type: filter.beneficiary_type,
            };
            }
            
            if (filter.currency) {
                where = {
                    ...where,
                currency: filter.currency,
            };
            }
            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            


      

      

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

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

    
};

