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

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

        const partner_targets = await db.partner_targets.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        partner_type: data.partner_type
        ||
        null
            ,
            
        website_url: data.website_url
        ||
        null
            ,
            
        contact_name: data.contact_name
        ||
        null
            ,
            
        contact_email: data.contact_email
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        last_contact_at: data.last_contact_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await partner_targets.setDeal_package( data.deal_package || null, {
            transaction,
        });
        
        await partner_targets.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return partner_targets;
    }
    

    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 partner_targetsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                partner_type: item.partner_type
            ||
            null
            ,
            
                website_url: item.website_url
            ||
            null
            ,
            
                contact_name: item.contact_name
            ||
            null
            ,
            
                contact_email: item.contact_email
            ||
            null
            ,
            
                notes: item.notes
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                last_contact_at: item.last_contact_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return partner_targets;
    }

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.partner_type !== undefined) updatePayload.partner_type = data.partner_type;
        
        
        if (data.website_url !== undefined) updatePayload.website_url = data.website_url;
        
        
        if (data.contact_name !== undefined) updatePayload.contact_name = data.contact_name;
        
        
        if (data.contact_email !== undefined) updatePayload.contact_email = data.contact_email;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.last_contact_at !== undefined) updatePayload.last_contact_at = data.last_contact_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.deal_package !== undefined) {
            await partner_targets.setDeal_package(
              
              data.deal_package,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await partner_targets.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return partner_targets;
    }

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

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

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


        return partner_targets;
    }

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

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

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

        await partner_targets.destroy({
            transaction
        });

        return partner_targets;
    }

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

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

        if (!partner_targets) {
            return partner_targets;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.deal_package = await partner_targets.getDeal_package({
            transaction
        });
        
        
        output.organizations = await partner_targets.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.deal_packages,
        as: 'deal_package',
        
        where: filter.deal_package ? {
          [Op.or]: [
            { id: { [Op.in]: filter.deal_package.split('|').map(term => Utils.uuid(term)) } },
            {
              title: {
                [Op.or]: filter.deal_package.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(
                        'partner_targets',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.website_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'partner_targets',
                        'website_url',
                        filter.website_url,
                    ),
                };
            }
            
            if (filter.contact_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'partner_targets',
                        'contact_name',
                        filter.contact_name,
                    ),
                };
            }
            
            if (filter.contact_email) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'partner_targets',
                        'contact_email',
                        filter.contact_email,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'partner_targets',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

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

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

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

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

            
            if (filter.partner_type) {
                where = {
                    ...where,
                partner_type: filter.partner_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.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.partner_targets.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(
                        'partner_targets',
                        'name',
                        query,
                    ),
                ],
            };
        }

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

    
};

