
const express = require('express');
const cors = require('cors');
const app = express();
const passport = require('passport');
const path = require('path');
const fs = require('fs');
const bodyParser = require('body-parser');
const db = require('./db/models');
const config = require('./config');
const swaggerUI = require('swagger-ui-express');
const swaggerJsDoc = require('swagger-jsdoc');

const authRoutes = require('./routes/auth');
const fileRoutes = require('./routes/file');
const searchRoutes = require('./routes/search');
const sqlRoutes = require('./routes/sql');
const pexelsRoutes = require('./routes/pexels');

const openaiRoutes = require('./routes/openai');



const usersRoutes = require('./routes/users');

const rolesRoutes = require('./routes/roles');

const permissionsRoutes = require('./routes/permissions');

const user_physical_baselinesRoutes = require('./routes/user_physical_baselines');

const user_lifestyle_baselinesRoutes = require('./routes/user_lifestyle_baselines');

const goalsRoutes = require('./routes/goals');

const conditionsRoutes = require('./routes/conditions');

const surgeriesRoutes = require('./routes/surgeries');

const implants_devicesRoutes = require('./routes/implants_devices');

const allergiesRoutes = require('./routes/allergies');

const family_historiesRoutes = require('./routes/family_histories');

const healthcare_providersRoutes = require('./routes/healthcare_providers');

const pharmaciesRoutes = require('./routes/pharmacies');

const medicationsRoutes = require('./routes/medications');

const medication_dosesRoutes = require('./routes/medication_doses');

const medication_side_effectsRoutes = require('./routes/medication_side_effects');

const supplementsRoutes = require('./routes/supplements');

const supplement_evidence_itemsRoutes = require('./routes/supplement_evidence_items');

const workoutsRoutes = require('./routes/workouts');

const exercisesRoutes = require('./routes/exercises');

const workout_exercisesRoutes = require('./routes/workout_exercises');

const workout_schedulesRoutes = require('./routes/workout_schedules');

const training_blocksRoutes = require('./routes/training_blocks');

const workout_sessionsRoutes = require('./routes/workout_sessions');

const strength_setsRoutes = require('./routes/strength_sets');

const cardio_sessionsRoutes = require('./routes/cardio_sessions');

const recovery_logsRoutes = require('./routes/recovery_logs');

const heat_cold_exposuresRoutes = require('./routes/heat_cold_exposures');

const flexibility_assessmentsRoutes = require('./routes/flexibility_assessments');

const foodsRoutes = require('./routes/foods');

const recipesRoutes = require('./routes/recipes');

const recipe_collectionsRoutes = require('./routes/recipe_collections');

const mealsRoutes = require('./routes/meals');

const meal_itemsRoutes = require('./routes/meal_items');

const nutrition_targetsRoutes = require('./routes/nutrition_targets');

const meal_plansRoutes = require('./routes/meal_plans');

const meal_plan_itemsRoutes = require('./routes/meal_plan_items');

const grocery_listsRoutes = require('./routes/grocery_lists');

const grocery_itemsRoutes = require('./routes/grocery_items');

const hydration_logsRoutes = require('./routes/hydration_logs');

const fasting_sessionsRoutes = require('./routes/fasting_sessions');

const ketone_glucose_logsRoutes = require('./routes/ketone_glucose_logs');

const bowel_movementsRoutes = require('./routes/bowel_movements');

const gut_symptom_logsRoutes = require('./routes/gut_symptom_logs');

const health_metricsRoutes = require('./routes/health_metrics');

const symptom_logsRoutes = require('./routes/symptom_logs');

const medical_appointmentsRoutes = require('./routes/medical_appointments');

const lab_documentsRoutes = require('./routes/lab_documents');

const vaccinationsRoutes = require('./routes/vaccinations');

const ai_chat_threadsRoutes = require('./routes/ai_chat_threads');

const ai_chat_messagesRoutes = require('./routes/ai_chat_messages');

const ai_generationsRoutes = require('./routes/ai_generations');

const habitsRoutes = require('./routes/habits');

const habit_logsRoutes = require('./routes/habit_logs');

const habit_challengesRoutes = require('./routes/habit_challenges');

const library_articlesRoutes = require('./routes/library_articles');

const saved_articlesRoutes = require('./routes/saved_articles');

const glossary_termsRoutes = require('./routes/glossary_terms');

const health_vault_documentsRoutes = require('./routes/health_vault_documents');

const emergency_medical_cardsRoutes = require('./routes/emergency_medical_cards');

const advance_directivesRoutes = require('./routes/advance_directives');

const insurance_policiesRoutes = require('./routes/insurance_policies');

const family_groupsRoutes = require('./routes/family_groups');

const family_membersRoutes = require('./routes/family_members');

const sharing_permissionsRoutes = require('./routes/sharing_permissions');

const mood_logsRoutes = require('./routes/mood_logs');

const mental_assessmentsRoutes = require('./routes/mental_assessments');

const journal_entriesRoutes = require('./routes/journal_entries');

const breathing_sessionsRoutes = require('./routes/breathing_sessions');

const stress_logsRoutes = require('./routes/stress_logs');

const cognitive_testsRoutes = require('./routes/cognitive_tests');

const sleep_logsRoutes = require('./routes/sleep_logs');

const sleep_environment_logsRoutes = require('./routes/sleep_environment_logs');

const nap_logsRoutes = require('./routes/nap_logs');

const menstrual_cyclesRoutes = require('./routes/menstrual_cycles');

const menstrual_day_logsRoutes = require('./routes/menstrual_day_logs');

const fertility_logsRoutes = require('./routes/fertility_logs');

const pregnanciesRoutes = require('./routes/pregnancies');

const pregnancy_symptom_logsRoutes = require('./routes/pregnancy_symptom_logs');

const breastfeeding_logsRoutes = require('./routes/breastfeeding_logs');

const formula_feeding_logsRoutes = require('./routes/formula_feeding_logs');

const baby_metricsRoutes = require('./routes/baby_metrics');

const epds_assessmentsRoutes = require('./routes/epds_assessments');

const kick_countsRoutes = require('./routes/kick_counts');

const contraction_sessionsRoutes = require('./routes/contraction_sessions');

const contractionsRoutes = require('./routes/contractions');

const menopause_symptom_logsRoutes = require('./routes/menopause_symptom_logs');

const male_reproductive_logsRoutes = require('./routes/male_reproductive_logs');

const semen_analysesRoutes = require('./routes/semen_analyses');

const sti_testsRoutes = require('./routes/sti_tests');

const contraception_logsRoutes = require('./routes/contraception_logs');

const libido_logsRoutes = require('./routes/libido_logs');

const sexual_activity_logsRoutes = require('./routes/sexual_activity_logs');

const skin_care_logsRoutes = require('./routes/skin_care_logs');

const sun_exposure_logsRoutes = require('./routes/sun_exposure_logs');

const mole_lesion_logsRoutes = require('./routes/mole_lesion_logs');

const oral_hygiene_logsRoutes = require('./routes/oral_hygiene_logs');

const dental_recordsRoutes = require('./routes/dental_records');

const dental_symptomsRoutes = require('./routes/dental_symptoms');

const vision_prescriptionsRoutes = require('./routes/vision_prescriptions');

const eye_symptom_logsRoutes = require('./routes/eye_symptom_logs');

const hearing_test_logsRoutes = require('./routes/hearing_test_logs');

const tinnitus_logsRoutes = require('./routes/tinnitus_logs');

const noise_exposure_logsRoutes = require('./routes/noise_exposure_logs');

const pain_logsRoutes = require('./routes/pain_logs');

const injuriesRoutes = require('./routes/injuries');

const physio_exercisesRoutes = require('./routes/physio_exercises');

const ergonomics_logsRoutes = require('./routes/ergonomics_logs');

const notificationsRoutes = require('./routes/notifications');

const export_jobsRoutes = require('./routes/export_jobs');

const app_settingsRoutes = require('./routes/app_settings');


const getBaseUrl = (url) => {
  if (!url) return '';
  return url.endsWith('/api') ? url.slice(0, -4) : url;
};

const options = {
  definition: {
    openapi: "3.0.0",
      info: {
        version: "1.0.0",
        title: "APEX BRAIN",
        description: "APEX BRAIN Online REST API for Testing and Prototyping application. You can perform all major operations with your entities - create, delete and etc.",
      },
    servers: [
      {
        url: getBaseUrl(process.env.NEXT_PUBLIC_BACK_API) || config.swaggerUrl,
        description: "Development server",
      }
    ],
    components: {
      securitySchemes: {
        bearerAuth: {
          type: 'http',
          scheme: 'bearer',
          bearerFormat: 'JWT',
        }
      },
      responses: {
        UnauthorizedError: {
          description: "Access token is missing or invalid"
        }
      }
    },
    security: [{
      bearerAuth: []
    }]
  },
  apis: ["./src/routes/*.js"],
};

const specs = swaggerJsDoc(options);
app.use('/api-docs', function (req, res, next) {
    swaggerUI.host = getBaseUrl(process.env.NEXT_PUBLIC_BACK_API) || req.get('host');
    next()
  }, swaggerUI.serve, swaggerUI.setup(specs))

app.use(cors({origin: true}));
require('./auth/auth');

app.use(bodyParser.json());

app.use('/api/auth', authRoutes);
app.use('/api/file', fileRoutes);
app.use('/api/pexels', pexelsRoutes);
app.enable('trust proxy');


app.use('/api/users', passport.authenticate('jwt', {session: false}), usersRoutes);

app.use('/api/roles', passport.authenticate('jwt', {session: false}), rolesRoutes);

app.use('/api/permissions', passport.authenticate('jwt', {session: false}), permissionsRoutes);

app.use('/api/user_physical_baselines', passport.authenticate('jwt', {session: false}), user_physical_baselinesRoutes);

app.use('/api/user_lifestyle_baselines', passport.authenticate('jwt', {session: false}), user_lifestyle_baselinesRoutes);

app.use('/api/goals', passport.authenticate('jwt', {session: false}), goalsRoutes);

app.use('/api/conditions', passport.authenticate('jwt', {session: false}), conditionsRoutes);

app.use('/api/surgeries', passport.authenticate('jwt', {session: false}), surgeriesRoutes);

app.use('/api/implants_devices', passport.authenticate('jwt', {session: false}), implants_devicesRoutes);

app.use('/api/allergies', passport.authenticate('jwt', {session: false}), allergiesRoutes);

app.use('/api/family_histories', passport.authenticate('jwt', {session: false}), family_historiesRoutes);

app.use('/api/healthcare_providers', passport.authenticate('jwt', {session: false}), healthcare_providersRoutes);

app.use('/api/pharmacies', passport.authenticate('jwt', {session: false}), pharmaciesRoutes);

app.use('/api/medications', passport.authenticate('jwt', {session: false}), medicationsRoutes);

app.use('/api/medication_doses', passport.authenticate('jwt', {session: false}), medication_dosesRoutes);

app.use('/api/medication_side_effects', passport.authenticate('jwt', {session: false}), medication_side_effectsRoutes);

app.use('/api/supplements', passport.authenticate('jwt', {session: false}), supplementsRoutes);

app.use('/api/supplement_evidence_items', passport.authenticate('jwt', {session: false}), supplement_evidence_itemsRoutes);

app.use('/api/workouts', passport.authenticate('jwt', {session: false}), workoutsRoutes);

app.use('/api/exercises', passport.authenticate('jwt', {session: false}), exercisesRoutes);

app.use('/api/workout_exercises', passport.authenticate('jwt', {session: false}), workout_exercisesRoutes);

app.use('/api/workout_schedules', passport.authenticate('jwt', {session: false}), workout_schedulesRoutes);

app.use('/api/training_blocks', passport.authenticate('jwt', {session: false}), training_blocksRoutes);

app.use('/api/workout_sessions', passport.authenticate('jwt', {session: false}), workout_sessionsRoutes);

app.use('/api/strength_sets', passport.authenticate('jwt', {session: false}), strength_setsRoutes);

app.use('/api/cardio_sessions', passport.authenticate('jwt', {session: false}), cardio_sessionsRoutes);

app.use('/api/recovery_logs', passport.authenticate('jwt', {session: false}), recovery_logsRoutes);

app.use('/api/heat_cold_exposures', passport.authenticate('jwt', {session: false}), heat_cold_exposuresRoutes);

app.use('/api/flexibility_assessments', passport.authenticate('jwt', {session: false}), flexibility_assessmentsRoutes);

app.use('/api/foods', passport.authenticate('jwt', {session: false}), foodsRoutes);

app.use('/api/recipes', passport.authenticate('jwt', {session: false}), recipesRoutes);

app.use('/api/recipe_collections', passport.authenticate('jwt', {session: false}), recipe_collectionsRoutes);

app.use('/api/meals', passport.authenticate('jwt', {session: false}), mealsRoutes);

app.use('/api/meal_items', passport.authenticate('jwt', {session: false}), meal_itemsRoutes);

app.use('/api/nutrition_targets', passport.authenticate('jwt', {session: false}), nutrition_targetsRoutes);

app.use('/api/meal_plans', passport.authenticate('jwt', {session: false}), meal_plansRoutes);

app.use('/api/meal_plan_items', passport.authenticate('jwt', {session: false}), meal_plan_itemsRoutes);

app.use('/api/grocery_lists', passport.authenticate('jwt', {session: false}), grocery_listsRoutes);

app.use('/api/grocery_items', passport.authenticate('jwt', {session: false}), grocery_itemsRoutes);

app.use('/api/hydration_logs', passport.authenticate('jwt', {session: false}), hydration_logsRoutes);

app.use('/api/fasting_sessions', passport.authenticate('jwt', {session: false}), fasting_sessionsRoutes);

app.use('/api/ketone_glucose_logs', passport.authenticate('jwt', {session: false}), ketone_glucose_logsRoutes);

app.use('/api/bowel_movements', passport.authenticate('jwt', {session: false}), bowel_movementsRoutes);

app.use('/api/gut_symptom_logs', passport.authenticate('jwt', {session: false}), gut_symptom_logsRoutes);

app.use('/api/health_metrics', passport.authenticate('jwt', {session: false}), health_metricsRoutes);

app.use('/api/symptom_logs', passport.authenticate('jwt', {session: false}), symptom_logsRoutes);

app.use('/api/medical_appointments', passport.authenticate('jwt', {session: false}), medical_appointmentsRoutes);

app.use('/api/lab_documents', passport.authenticate('jwt', {session: false}), lab_documentsRoutes);

app.use('/api/vaccinations', passport.authenticate('jwt', {session: false}), vaccinationsRoutes);

app.use('/api/ai_chat_threads', passport.authenticate('jwt', {session: false}), ai_chat_threadsRoutes);

app.use('/api/ai_chat_messages', passport.authenticate('jwt', {session: false}), ai_chat_messagesRoutes);

app.use('/api/ai_generations', passport.authenticate('jwt', {session: false}), ai_generationsRoutes);

app.use('/api/habits', passport.authenticate('jwt', {session: false}), habitsRoutes);

app.use('/api/habit_logs', passport.authenticate('jwt', {session: false}), habit_logsRoutes);

app.use('/api/habit_challenges', passport.authenticate('jwt', {session: false}), habit_challengesRoutes);

app.use('/api/library_articles', passport.authenticate('jwt', {session: false}), library_articlesRoutes);

app.use('/api/saved_articles', passport.authenticate('jwt', {session: false}), saved_articlesRoutes);

app.use('/api/glossary_terms', passport.authenticate('jwt', {session: false}), glossary_termsRoutes);

app.use('/api/health_vault_documents', passport.authenticate('jwt', {session: false}), health_vault_documentsRoutes);

app.use('/api/emergency_medical_cards', passport.authenticate('jwt', {session: false}), emergency_medical_cardsRoutes);

app.use('/api/advance_directives', passport.authenticate('jwt', {session: false}), advance_directivesRoutes);

app.use('/api/insurance_policies', passport.authenticate('jwt', {session: false}), insurance_policiesRoutes);

app.use('/api/family_groups', passport.authenticate('jwt', {session: false}), family_groupsRoutes);

app.use('/api/family_members', passport.authenticate('jwt', {session: false}), family_membersRoutes);

app.use('/api/sharing_permissions', passport.authenticate('jwt', {session: false}), sharing_permissionsRoutes);

app.use('/api/mood_logs', passport.authenticate('jwt', {session: false}), mood_logsRoutes);

app.use('/api/mental_assessments', passport.authenticate('jwt', {session: false}), mental_assessmentsRoutes);

app.use('/api/journal_entries', passport.authenticate('jwt', {session: false}), journal_entriesRoutes);

app.use('/api/breathing_sessions', passport.authenticate('jwt', {session: false}), breathing_sessionsRoutes);

app.use('/api/stress_logs', passport.authenticate('jwt', {session: false}), stress_logsRoutes);

app.use('/api/cognitive_tests', passport.authenticate('jwt', {session: false}), cognitive_testsRoutes);

app.use('/api/sleep_logs', passport.authenticate('jwt', {session: false}), sleep_logsRoutes);

app.use('/api/sleep_environment_logs', passport.authenticate('jwt', {session: false}), sleep_environment_logsRoutes);

app.use('/api/nap_logs', passport.authenticate('jwt', {session: false}), nap_logsRoutes);

app.use('/api/menstrual_cycles', passport.authenticate('jwt', {session: false}), menstrual_cyclesRoutes);

app.use('/api/menstrual_day_logs', passport.authenticate('jwt', {session: false}), menstrual_day_logsRoutes);

app.use('/api/fertility_logs', passport.authenticate('jwt', {session: false}), fertility_logsRoutes);

app.use('/api/pregnancies', passport.authenticate('jwt', {session: false}), pregnanciesRoutes);

app.use('/api/pregnancy_symptom_logs', passport.authenticate('jwt', {session: false}), pregnancy_symptom_logsRoutes);

app.use('/api/breastfeeding_logs', passport.authenticate('jwt', {session: false}), breastfeeding_logsRoutes);

app.use('/api/formula_feeding_logs', passport.authenticate('jwt', {session: false}), formula_feeding_logsRoutes);

app.use('/api/baby_metrics', passport.authenticate('jwt', {session: false}), baby_metricsRoutes);

app.use('/api/epds_assessments', passport.authenticate('jwt', {session: false}), epds_assessmentsRoutes);

app.use('/api/kick_counts', passport.authenticate('jwt', {session: false}), kick_countsRoutes);

app.use('/api/contraction_sessions', passport.authenticate('jwt', {session: false}), contraction_sessionsRoutes);

app.use('/api/contractions', passport.authenticate('jwt', {session: false}), contractionsRoutes);

app.use('/api/menopause_symptom_logs', passport.authenticate('jwt', {session: false}), menopause_symptom_logsRoutes);

app.use('/api/male_reproductive_logs', passport.authenticate('jwt', {session: false}), male_reproductive_logsRoutes);

app.use('/api/semen_analyses', passport.authenticate('jwt', {session: false}), semen_analysesRoutes);

app.use('/api/sti_tests', passport.authenticate('jwt', {session: false}), sti_testsRoutes);

app.use('/api/contraception_logs', passport.authenticate('jwt', {session: false}), contraception_logsRoutes);

app.use('/api/libido_logs', passport.authenticate('jwt', {session: false}), libido_logsRoutes);

app.use('/api/sexual_activity_logs', passport.authenticate('jwt', {session: false}), sexual_activity_logsRoutes);

app.use('/api/skin_care_logs', passport.authenticate('jwt', {session: false}), skin_care_logsRoutes);

app.use('/api/sun_exposure_logs', passport.authenticate('jwt', {session: false}), sun_exposure_logsRoutes);

app.use('/api/mole_lesion_logs', passport.authenticate('jwt', {session: false}), mole_lesion_logsRoutes);

app.use('/api/oral_hygiene_logs', passport.authenticate('jwt', {session: false}), oral_hygiene_logsRoutes);

app.use('/api/dental_records', passport.authenticate('jwt', {session: false}), dental_recordsRoutes);

app.use('/api/dental_symptoms', passport.authenticate('jwt', {session: false}), dental_symptomsRoutes);

app.use('/api/vision_prescriptions', passport.authenticate('jwt', {session: false}), vision_prescriptionsRoutes);

app.use('/api/eye_symptom_logs', passport.authenticate('jwt', {session: false}), eye_symptom_logsRoutes);

app.use('/api/hearing_test_logs', passport.authenticate('jwt', {session: false}), hearing_test_logsRoutes);

app.use('/api/tinnitus_logs', passport.authenticate('jwt', {session: false}), tinnitus_logsRoutes);

app.use('/api/noise_exposure_logs', passport.authenticate('jwt', {session: false}), noise_exposure_logsRoutes);

app.use('/api/pain_logs', passport.authenticate('jwt', {session: false}), pain_logsRoutes);

app.use('/api/injuries', passport.authenticate('jwt', {session: false}), injuriesRoutes);

app.use('/api/physio_exercises', passport.authenticate('jwt', {session: false}), physio_exercisesRoutes);

app.use('/api/ergonomics_logs', passport.authenticate('jwt', {session: false}), ergonomics_logsRoutes);

app.use('/api/notifications', passport.authenticate('jwt', {session: false}), notificationsRoutes);

app.use('/api/export_jobs', passport.authenticate('jwt', {session: false}), export_jobsRoutes);

app.use('/api/app_settings', passport.authenticate('jwt', {session: false}), app_settingsRoutes);

app.use(
    '/api/openai',
    passport.authenticate('jwt', { session: false }),
    openaiRoutes,
);
app.use(
    '/api/ai',
    passport.authenticate('jwt', { session: false }),
    openaiRoutes,
);

app.use(
  '/api/search',
  passport.authenticate('jwt', { session: false }),
  searchRoutes);
app.use(
  '/api/sql',
  passport.authenticate('jwt', { session: false }),
  sqlRoutes);

  
const publicDir = path.join(
  __dirname,
  '../public',
);

if (fs.existsSync(publicDir)) {
  app.use('/', express.static(publicDir));

  app.get('*', function(request, response) {
    response.sendFile(
      path.resolve(publicDir, 'index.html'),
    );
  });
}

const PORT = process.env.NODE_ENV === 'dev_stage' ? 3000 : 8080;

  app.listen(PORT, () => {
    console.log(`Listening on port ${PORT}`);
  });

module.exports = app;
