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

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

        const user_profiles = await db.user_profiles.create(
            {
                id: data.id || undefined,
        
        cpf: data.cpf
        ||
        null
            ,
            
        birth_date: data.birth_date
        ||
        null
            ,
            
        marital_status: data.marital_status
        ||
        null
            ,
            
        spouse_cpf: data.spouse_cpf
        ||
        null
            ,
            
        spouse_name: data.spouse_name
        ||
        null
            ,
            
        mother_name: data.mother_name
        ||
        null
            ,
            
        cep: data.cep
        ||
        null
            ,
            
        street: data.street
        ||
        null
            ,
            
        house_number: data.house_number
        ||
        null
            ,
            
        address_complement: data.address_complement
        ||
        null
            ,
            
        neighborhood: data.neighborhood
        ||
        null
            ,
            
        city: data.city
        ||
        null
            ,
            
        state_uf: data.state_uf
        ||
        null
            ,
            
        phone: data.phone
        ||
        null
            ,
            
        occupation_text: data.occupation_text
        ||
        null
            ,
            
        occupation_code: data.occupation_code
        ||
        null
            ,
            
        cbo_code: data.cbo_code
        ||
        null
            ,
            
        main_source_cnpj: data.main_source_cnpj
        ||
        null
            ,
            
        voter_title: data.voter_title
        ||
        null
            ,
            
        voter_zone: data.voter_zone
        ||
        null
            ,
            
        voter_section: data.voter_section
        ||
        null
            ,
            
        nit_pis_pasep: data.nit_pis_pasep
        ||
        null
            ,
            
        caepf_number: data.caepf_number
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await user_profiles.setUser( data.user || null, {
            transaction,
        });
        
        await user_profiles.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return user_profiles;
    }
    

    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 user_profilesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                cpf: item.cpf
            ||
            null
            ,
            
                birth_date: item.birth_date
            ||
            null
            ,
            
                marital_status: item.marital_status
            ||
            null
            ,
            
                spouse_cpf: item.spouse_cpf
            ||
            null
            ,
            
                spouse_name: item.spouse_name
            ||
            null
            ,
            
                mother_name: item.mother_name
            ||
            null
            ,
            
                cep: item.cep
            ||
            null
            ,
            
                street: item.street
            ||
            null
            ,
            
                house_number: item.house_number
            ||
            null
            ,
            
                address_complement: item.address_complement
            ||
            null
            ,
            
                neighborhood: item.neighborhood
            ||
            null
            ,
            
                city: item.city
            ||
            null
            ,
            
                state_uf: item.state_uf
            ||
            null
            ,
            
                phone: item.phone
            ||
            null
            ,
            
                occupation_text: item.occupation_text
            ||
            null
            ,
            
                occupation_code: item.occupation_code
            ||
            null
            ,
            
                cbo_code: item.cbo_code
            ||
            null
            ,
            
                main_source_cnpj: item.main_source_cnpj
            ||
            null
            ,
            
                voter_title: item.voter_title
            ||
            null
            ,
            
                voter_zone: item.voter_zone
            ||
            null
            ,
            
                voter_section: item.voter_section
            ||
            null
            ,
            
                nit_pis_pasep: item.nit_pis_pasep
            ||
            null
            ,
            
                caepf_number: item.caepf_number
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return user_profiles;
    }

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


        

        const updatePayload = {};
        
        if (data.cpf !== undefined) updatePayload.cpf = data.cpf;
        
        
        if (data.birth_date !== undefined) updatePayload.birth_date = data.birth_date;
        
        
        if (data.marital_status !== undefined) updatePayload.marital_status = data.marital_status;
        
        
        if (data.spouse_cpf !== undefined) updatePayload.spouse_cpf = data.spouse_cpf;
        
        
        if (data.spouse_name !== undefined) updatePayload.spouse_name = data.spouse_name;
        
        
        if (data.mother_name !== undefined) updatePayload.mother_name = data.mother_name;
        
        
        if (data.cep !== undefined) updatePayload.cep = data.cep;
        
        
        if (data.street !== undefined) updatePayload.street = data.street;
        
        
        if (data.house_number !== undefined) updatePayload.house_number = data.house_number;
        
        
        if (data.address_complement !== undefined) updatePayload.address_complement = data.address_complement;
        
        
        if (data.neighborhood !== undefined) updatePayload.neighborhood = data.neighborhood;
        
        
        if (data.city !== undefined) updatePayload.city = data.city;
        
        
        if (data.state_uf !== undefined) updatePayload.state_uf = data.state_uf;
        
        
        if (data.phone !== undefined) updatePayload.phone = data.phone;
        
        
        if (data.occupation_text !== undefined) updatePayload.occupation_text = data.occupation_text;
        
        
        if (data.occupation_code !== undefined) updatePayload.occupation_code = data.occupation_code;
        
        
        if (data.cbo_code !== undefined) updatePayload.cbo_code = data.cbo_code;
        
        
        if (data.main_source_cnpj !== undefined) updatePayload.main_source_cnpj = data.main_source_cnpj;
        
        
        if (data.voter_title !== undefined) updatePayload.voter_title = data.voter_title;
        
        
        if (data.voter_zone !== undefined) updatePayload.voter_zone = data.voter_zone;
        
        
        if (data.voter_section !== undefined) updatePayload.voter_section = data.voter_section;
        
        
        if (data.nit_pis_pasep !== undefined) updatePayload.nit_pis_pasep = data.nit_pis_pasep;
        
        
        if (data.caepf_number !== undefined) updatePayload.caepf_number = data.caepf_number;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.user !== undefined) {
            await user_profiles.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await user_profiles.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return user_profiles;
    }

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

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

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


        return user_profiles;
    }

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

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

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

        await user_profiles.destroy({
            transaction
        });

        return user_profiles;
    }

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

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

        if (!user_profiles) {
            return user_profiles;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await user_profiles.getUser({
            transaction
        });
        
        
        output.organizations = await user_profiles.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.users,
        as: 'user',
        
        where: filter.user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.user.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.cpf) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'user_profiles',
                        'cpf',
                        filter.cpf,
                    ),
                };
            }
            
            if (filter.spouse_cpf) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'user_profiles',
                        'spouse_cpf',
                        filter.spouse_cpf,
                    ),
                };
            }
            
            if (filter.spouse_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'user_profiles',
                        'spouse_name',
                        filter.spouse_name,
                    ),
                };
            }
            
            if (filter.mother_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'user_profiles',
                        'mother_name',
                        filter.mother_name,
                    ),
                };
            }
            
            if (filter.cep) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'user_profiles',
                        'cep',
                        filter.cep,
                    ),
                };
            }
            
            if (filter.street) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'user_profiles',
                        'street',
                        filter.street,
                    ),
                };
            }
            
            if (filter.house_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'user_profiles',
                        'house_number',
                        filter.house_number,
                    ),
                };
            }
            
            if (filter.address_complement) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'user_profiles',
                        'address_complement',
                        filter.address_complement,
                    ),
                };
            }
            
            if (filter.neighborhood) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'user_profiles',
                        'neighborhood',
                        filter.neighborhood,
                    ),
                };
            }
            
            if (filter.city) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'user_profiles',
                        'city',
                        filter.city,
                    ),
                };
            }
            
            if (filter.state_uf) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'user_profiles',
                        'state_uf',
                        filter.state_uf,
                    ),
                };
            }
            
            if (filter.phone) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'user_profiles',
                        'phone',
                        filter.phone,
                    ),
                };
            }
            
            if (filter.occupation_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'user_profiles',
                        'occupation_text',
                        filter.occupation_text,
                    ),
                };
            }
            
            if (filter.occupation_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'user_profiles',
                        'occupation_code',
                        filter.occupation_code,
                    ),
                };
            }
            
            if (filter.cbo_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'user_profiles',
                        'cbo_code',
                        filter.cbo_code,
                    ),
                };
            }
            
            if (filter.main_source_cnpj) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'user_profiles',
                        'main_source_cnpj',
                        filter.main_source_cnpj,
                    ),
                };
            }
            
            if (filter.voter_title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'user_profiles',
                        'voter_title',
                        filter.voter_title,
                    ),
                };
            }
            
            if (filter.voter_zone) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'user_profiles',
                        'voter_zone',
                        filter.voter_zone,
                    ),
                };
            }
            
            if (filter.voter_section) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'user_profiles',
                        'voter_section',
                        filter.voter_section,
                    ),
                };
            }
            
            if (filter.nit_pis_pasep) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'user_profiles',
                        'nit_pis_pasep',
                        filter.nit_pis_pasep,
                    ),
                };
            }
            
            if (filter.caepf_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'user_profiles',
                        'caepf_number',
                        filter.caepf_number,
                    ),
                };
            }
            

            
            

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

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

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

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

            
            if (filter.marital_status) {
                where = {
                    ...where,
                marital_status: filter.marital_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.user_profiles.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(
                        'user_profiles',
                        'cpf',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

