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

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

        const deal_packages = await db.deal_packages.create(
            {
                id: data.id || undefined,
        
        title: data.title
        ||
        null
            ,
            
        deal_type: data.deal_type
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        target_price: data.target_price
        ||
        null
            ,
            
        down_payment: data.down_payment
        ||
        null
            ,
            
        seller_note_amount: data.seller_note_amount
        ||
        null
            ,
            
        interest_rate: data.interest_rate
        ||
        null
            ,
            
        term_months: data.term_months
        ||
        null
            ,
            
        structure_overview: data.structure_overview
        ||
        null
            ,
            
        risk_factors: data.risk_factors
        ||
        null
            ,
            
        next_steps: data.next_steps
        ||
        null
            ,
            
        created_at_time: data.created_at_time
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await deal_packages.setProject( data.project || null, {
            transaction,
        });
        
        await deal_packages.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        
        await deal_packages.setPartner_targets(data.partner_targets || [], {
            transaction,
        });
        

        

        return deal_packages;
    }
    

    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 deal_packagesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                title: item.title
            ||
            null
            ,
            
                deal_type: item.deal_type
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                target_price: item.target_price
            ||
            null
            ,
            
                down_payment: item.down_payment
            ||
            null
            ,
            
                seller_note_amount: item.seller_note_amount
            ||
            null
            ,
            
                interest_rate: item.interest_rate
            ||
            null
            ,
            
                term_months: item.term_months
            ||
            null
            ,
            
                structure_overview: item.structure_overview
            ||
            null
            ,
            
                risk_factors: item.risk_factors
            ||
            null
            ,
            
                next_steps: item.next_steps
            ||
            null
            ,
            
                created_at_time: item.created_at_time
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return deal_packages;
    }

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


        

        const updatePayload = {};
        
        if (data.title !== undefined) updatePayload.title = data.title;
        
        
        if (data.deal_type !== undefined) updatePayload.deal_type = data.deal_type;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.target_price !== undefined) updatePayload.target_price = data.target_price;
        
        
        if (data.down_payment !== undefined) updatePayload.down_payment = data.down_payment;
        
        
        if (data.seller_note_amount !== undefined) updatePayload.seller_note_amount = data.seller_note_amount;
        
        
        if (data.interest_rate !== undefined) updatePayload.interest_rate = data.interest_rate;
        
        
        if (data.term_months !== undefined) updatePayload.term_months = data.term_months;
        
        
        if (data.structure_overview !== undefined) updatePayload.structure_overview = data.structure_overview;
        
        
        if (data.risk_factors !== undefined) updatePayload.risk_factors = data.risk_factors;
        
        
        if (data.next_steps !== undefined) updatePayload.next_steps = data.next_steps;
        
        
        if (data.created_at_time !== undefined) updatePayload.created_at_time = data.created_at_time;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.project !== undefined) {
            await deal_packages.setProject(
              
              data.project,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await deal_packages.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        
        if (data.partner_targets !== undefined) {
            await deal_packages.setPartner_targets(data.partner_targets, { transaction });
        }
        

        

        return deal_packages;
    }

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

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

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


        return deal_packages;
    }

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

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

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

        await deal_packages.destroy({
            transaction
        });

        return deal_packages;
    }

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

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

        if (!deal_packages) {
            return deal_packages;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.partner_targets_deal_package = await deal_packages.getPartner_targets_deal_package({
            transaction
        });
        
        
        
        
        output.project = await deal_packages.getProject({
            transaction
        });
        
        
        output.partner_targets = await deal_packages.getPartner_targets({
            transaction
        });
        
        
        output.organizations = await deal_packages.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.projects,
        as: 'project',
        
        where: filter.project ? {
          [Op.or]: [
            { id: { [Op.in]: filter.project.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.project.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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


      {
        model: db.partner_targets,
        as: 'partner_targets',
        required: false,
      },


    ];

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

            
            if (filter.title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'deal_packages',
                        'title',
                        filter.title,
                    ),
                };
            }
            
            if (filter.structure_overview) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'deal_packages',
                        'structure_overview',
                        filter.structure_overview,
                    ),
                };
            }
            
            if (filter.risk_factors) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'deal_packages',
                        'risk_factors',
                        filter.risk_factors,
                    ),
                };
            }
            
            if (filter.next_steps) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'deal_packages',
                        'next_steps',
                        filter.next_steps,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
            if (filter.deal_type) {
                where = {
                    ...where,
                deal_type: filter.deal_type,
            };
            }
            
            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.partner_targets) {
        const searchTerms = filter.partner_targets.split('|');

        include = [
          {
            model: db.partner_targets,
            as: 'partner_targets_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  name: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }


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

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

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

    
};

