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

const coursesRoutes = require('./routes/courses');

const lessonsRoutes = require('./routes/lessons');

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

const gamesRoutes = require('./routes/games');

const interactive_activitiesRoutes = require('./routes/interactive_activities');

const content_itemsRoutes = require('./routes/content_items');

const learning_pathsRoutes = require('./routes/learning_paths');

const enrollmentsRoutes = require('./routes/enrollments');

const progress_recordsRoutes = require('./routes/progress_records');

const attemptsRoutes = require('./routes/attempts');

const leaderboardsRoutes = require('./routes/leaderboards');

const leaderboard_entriesRoutes = require('./routes/leaderboard_entries');

const ai_mentor_profilesRoutes = require('./routes/ai_mentor_profiles');

const mentor_conversationsRoutes = require('./routes/mentor_conversations');

const mentor_messagesRoutes = require('./routes/mentor_messages');

const problem_reportsRoutes = require('./routes/problem_reports');

const solution_proposalsRoutes = require('./routes/solution_proposals');

const votesRoutes = require('./routes/votes');

const commentsRoutes = require('./routes/comments');

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

const badgesRoutes = require('./routes/badges');

const user_badgesRoutes = require('./routes/user_badges');

const eventsRoutes = require('./routes/events');

const event_registrationsRoutes = require('./routes/event_registrations');

const site_pagesRoutes = require('./routes/site_pages');


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: "KillNet Education Platform",
        description: "KillNet Education Platform 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/organizations', passport.authenticate('jwt', {session: false}), organizationsRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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;

db.sequelize.sync().then(function () {
  app.listen(PORT, () => {
    console.log(`Listening on port ${PORT}`);
  });
});

module.exports = app;
