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

const avatar_customizationsRoutes = require('./routes/avatar_customizations');

const cosmeticsRoutes = require('./routes/cosmetics');

const boxesRoutes = require('./routes/boxes');

const box_itemsRoutes = require('./routes/box_items');

const purchasesRoutes = require('./routes/purchases');

const inventory_itemsRoutes = require('./routes/inventory_items');

const titlesRoutes = require('./routes/titles');

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

const achievementsRoutes = require('./routes/achievements');

const user_achievementsRoutes = require('./routes/user_achievements');

const quizzesRoutes = require('./routes/quizzes');

const quiz_questionsRoutes = require('./routes/quiz_questions');

const question_answersRoutes = require('./routes/question_answers');

const quiz_tagsRoutes = require('./routes/quiz_tags');

const quiz_tag_linksRoutes = require('./routes/quiz_tag_links');

const orbix_quiz_assistant_sessionsRoutes = require('./routes/orbix_quiz_assistant_sessions');

const game_modesRoutes = require('./routes/game_modes');

const matchesRoutes = require('./routes/matches');

const match_playersRoutes = require('./routes/match_players');

const match_questionsRoutes = require('./routes/match_questions');

const player_answersRoutes = require('./routes/player_answers');

const wheel_eventsRoutes = require('./routes/wheel_events');

const music_playlistsRoutes = require('./routes/music_playlists');

const music_tracksRoutes = require('./routes/music_tracks');

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

const daily_rewardsRoutes = require('./routes/daily_rewards');

const moderation_reportsRoutes = require('./routes/moderation_reports');

const community_modesRoutes = require('./routes/community_modes');

const community_mode_build_sessionsRoutes = require('./routes/community_mode_build_sessions');

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


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: "App Preview",
        description: "App Preview 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/avatars', passport.authenticate('jwt', {session: false}), avatarsRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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;
