
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 organizationForAuthRoutes = require('./routes/organizationLogin');

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



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

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

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

const accountsRoutes = require('./routes/accounts');

const patientsRoutes = require('./routes/patients');

const patient_access_grantsRoutes = require('./routes/patient_access_grants');

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

const medication_schedulesRoutes = require('./routes/medication_schedules');

const calendar_eventsRoutes = require('./routes/calendar_events');

const remindersRoutes = require('./routes/reminders');

const cognitive_programsRoutes = require('./routes/cognitive_programs');

const cognitive_exercisesRoutes = require('./routes/cognitive_exercises');

const cognitive_sessionsRoutes = require('./routes/cognitive_sessions');

const cognitive_attemptsRoutes = require('./routes/cognitive_attempts');

const stage_assessmentsRoutes = require('./routes/stage_assessments');

const voice_assistant_sessionsRoutes = require('./routes/voice_assistant_sessions');

const iot_devicesRoutes = require('./routes/iot_devices');

const iot_telemetry_eventsRoutes = require('./routes/iot_telemetry_events');

const geofencesRoutes = require('./routes/geofences');

const alertsRoutes = require('./routes/alerts');

const alert_notificationsRoutes = require('./routes/alert_notifications');

const shared_dashboard_postsRoutes = require('./routes/shared_dashboard_posts');

const scientific_articlesRoutes = require('./routes/scientific_articles');

const article_recommendationsRoutes = require('./routes/article_recommendations');

const clinical_reportsRoutes = require('./routes/clinical_reports');

const admin_metrics_snapshotsRoutes = require('./routes/admin_metrics_snapshots');


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: "Plateforme Alzheimer Care",
        description: "Plateforme Alzheimer Care 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/accounts', passport.authenticate('jwt', {session: false}), accountsRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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);

app.use(
  '/api/org-for-auth',
  organizationForAuthRoutes,
  );

  
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;
