const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');

module.exports = function(sequelize, DataTypes) {
  const users = sequelize.define(
    'users',
    {
      id: {
        type: DataTypes.UUID,
        defaultValue: DataTypes.UUIDV4,
        primaryKey: true,
      },

firstName: {
        type: DataTypes.TEXT,
      
      

      },

lastName: {
        type: DataTypes.TEXT,
      
      

      },

phoneNumber: {
        type: DataTypes.TEXT,
      
      

      },

email: {
        type: DataTypes.TEXT,
      
      

      },

disabled: {
        type: DataTypes.BOOLEAN,
      
        allowNull: false,
        defaultValue: false,
      
      

      },

password: {
        type: DataTypes.TEXT,
      
      

      },

emailVerified: {
        type: DataTypes.BOOLEAN,
      
        allowNull: false,
        defaultValue: false,
      
      

      },

emailVerificationToken: {
        type: DataTypes.TEXT,
      
      

      },

emailVerificationTokenExpiresAt: {
        type: DataTypes.DATE,
      
      

      },

passwordResetToken: {
        type: DataTypes.TEXT,
      
      

      },

passwordResetTokenExpiresAt: {
        type: DataTypes.DATE,
      
      

      },

provider: {
        type: DataTypes.TEXT,
      
      

      },

      importHash: {
        type: DataTypes.STRING(255),
        allowNull: true,
        unique: true,
      },
    },
    {
      timestamps: true,
      paranoid: true,
      freezeTableName: true,
    },
  );

  users.associate = (db) => {

    db.users.belongsToMany(db.permissions, {
      as: 'custom_permissions',
      foreignKey: {
        name: 'users_custom_permissionsId',
      },
      constraints: false,
      through: 'usersCustom_permissionsPermissions',
    });

    db.users.belongsToMany(db.permissions, {
      as: 'custom_permissions_filter',
      foreignKey: {
        name: 'users_custom_permissionsId',
      },
      constraints: false,
      through: 'usersCustom_permissionsPermissions',
    });


/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity





    db.users.hasMany(db.user_physical_baselines, {
      as: 'user_physical_baselines_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.user_lifestyle_baselines, {
      as: 'user_lifestyle_baselines_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.goals, {
      as: 'goals_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.conditions, {
      as: 'conditions_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.surgeries, {
      as: 'surgeries_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.implants_devices, {
      as: 'implants_devices_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.allergies, {
      as: 'allergies_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.family_histories, {
      as: 'family_histories_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.healthcare_providers, {
      as: 'healthcare_providers_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.pharmacies, {
      as: 'pharmacies_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.medications, {
      as: 'medications_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });




    db.users.hasMany(db.supplements, {
      as: 'supplements_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });






    db.users.hasMany(db.workout_schedules, {
      as: 'workout_schedules_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.training_blocks, {
      as: 'training_blocks_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.workout_sessions, {
      as: 'workout_sessions_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });



    db.users.hasMany(db.cardio_sessions, {
      as: 'cardio_sessions_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.recovery_logs, {
      as: 'recovery_logs_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.heat_cold_exposures, {
      as: 'heat_cold_exposures_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.flexibility_assessments, {
      as: 'flexibility_assessments_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });



    db.users.hasMany(db.recipes, {
      as: 'recipes_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.recipe_collections, {
      as: 'recipe_collections_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.meals, {
      as: 'meals_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });



    db.users.hasMany(db.nutrition_targets, {
      as: 'nutrition_targets_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.meal_plans, {
      as: 'meal_plans_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });



    db.users.hasMany(db.grocery_lists, {
      as: 'grocery_lists_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });



    db.users.hasMany(db.hydration_logs, {
      as: 'hydration_logs_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.fasting_sessions, {
      as: 'fasting_sessions_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.ketone_glucose_logs, {
      as: 'ketone_glucose_logs_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.bowel_movements, {
      as: 'bowel_movements_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.gut_symptom_logs, {
      as: 'gut_symptom_logs_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.health_metrics, {
      as: 'health_metrics_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.symptom_logs, {
      as: 'symptom_logs_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.medical_appointments, {
      as: 'medical_appointments_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.lab_documents, {
      as: 'lab_documents_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.vaccinations, {
      as: 'vaccinations_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.ai_chat_threads, {
      as: 'ai_chat_threads_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });



    db.users.hasMany(db.ai_generations, {
      as: 'ai_generations_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.habits, {
      as: 'habits_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });



    db.users.hasMany(db.habit_challenges, {
      as: 'habit_challenges_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });



    db.users.hasMany(db.saved_articles, {
      as: 'saved_articles_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });



    db.users.hasMany(db.health_vault_documents, {
      as: 'health_vault_documents_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.emergency_medical_cards, {
      as: 'emergency_medical_cards_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.advance_directives, {
      as: 'advance_directives_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.insurance_policies, {
      as: 'insurance_policies_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.family_groups, {
      as: 'family_groups_owner_user',
      foreignKey: {
          name: 'owner_userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.family_members, {
      as: 'family_members_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.sharing_permissions, {
      as: 'sharing_permissions_granter_user',
      foreignKey: {
          name: 'granter_userId',
      },
      constraints: false,
    });

    db.users.hasMany(db.sharing_permissions, {
      as: 'sharing_permissions_grantee_user',
      foreignKey: {
          name: 'grantee_userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.mood_logs, {
      as: 'mood_logs_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.mental_assessments, {
      as: 'mental_assessments_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.journal_entries, {
      as: 'journal_entries_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.breathing_sessions, {
      as: 'breathing_sessions_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.stress_logs, {
      as: 'stress_logs_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.cognitive_tests, {
      as: 'cognitive_tests_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.sleep_logs, {
      as: 'sleep_logs_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.sleep_environment_logs, {
      as: 'sleep_environment_logs_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.nap_logs, {
      as: 'nap_logs_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.menstrual_cycles, {
      as: 'menstrual_cycles_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });



    db.users.hasMany(db.fertility_logs, {
      as: 'fertility_logs_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.pregnancies, {
      as: 'pregnancies_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });










    db.users.hasMany(db.menopause_symptom_logs, {
      as: 'menopause_symptom_logs_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.male_reproductive_logs, {
      as: 'male_reproductive_logs_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.semen_analyses, {
      as: 'semen_analyses_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.sti_tests, {
      as: 'sti_tests_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.contraception_logs, {
      as: 'contraception_logs_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.libido_logs, {
      as: 'libido_logs_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.sexual_activity_logs, {
      as: 'sexual_activity_logs_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.skin_care_logs, {
      as: 'skin_care_logs_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.sun_exposure_logs, {
      as: 'sun_exposure_logs_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.mole_lesion_logs, {
      as: 'mole_lesion_logs_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.oral_hygiene_logs, {
      as: 'oral_hygiene_logs_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.dental_records, {
      as: 'dental_records_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.dental_symptoms, {
      as: 'dental_symptoms_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.vision_prescriptions, {
      as: 'vision_prescriptions_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.eye_symptom_logs, {
      as: 'eye_symptom_logs_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.hearing_test_logs, {
      as: 'hearing_test_logs_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.tinnitus_logs, {
      as: 'tinnitus_logs_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.noise_exposure_logs, {
      as: 'noise_exposure_logs_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.pain_logs, {
      as: 'pain_logs_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.injuries, {
      as: 'injuries_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });



    db.users.hasMany(db.ergonomics_logs, {
      as: 'ergonomics_logs_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.notifications, {
      as: 'notifications_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.export_jobs, {
      as: 'export_jobs_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.app_settings, {
      as: 'app_settings_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });



//end loop



    db.users.belongsTo(db.roles, {
      as: 'app_role',
      foreignKey: {
        name: 'app_roleId',
      },
      constraints: false,
    });



    db.users.hasMany(db.file, {
      as: 'avatar',
      foreignKey: 'belongsToId',
      constraints: false,
      scope: {
        belongsTo: db.users.getTableName(),
        belongsToColumn: 'avatar',
      },
    });


    db.users.belongsTo(db.users, {
      as: 'createdBy',
    });

    db.users.belongsTo(db.users, {
      as: 'updatedBy',
    });
  };


    users.beforeCreate((users, options) => {
        users = trimStringFields(users);

    if (users.provider !== providers.LOCAL && Object.values(providers).indexOf(users.provider) > -1) {
        users.emailVerified = true;

        if (!users.password) {
            const password = crypto
                .randomBytes(20)
                .toString('hex');

            const hashedPassword = bcrypt.hashSync(
            password,
            config.bcrypt.saltRounds,
        );

            users.password = hashedPassword
            }
        }
    });

  users.beforeUpdate((users, options) => {
    users = trimStringFields(users);
  });
  

  return users;
};


function trimStringFields(users) {
  users.email = users.email.trim();

  users.firstName = users.firstName
    ? users.firstName.trim()
    : null;

  users.lastName = users.lastName
    ? users.lastName.trim()
    : null;

  return users;
}

