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

const api_request_logsRoutes = require('./routes/api_request_logs');

const sync_jobsRoutes = require('./routes/sync_jobs');

const beatmap_setsRoutes = require('./routes/beatmap_sets');

const mappersRoutes = require('./routes/mappers');

const artistsRoutes = require('./routes/artists');

const beatmapsRoutes = require('./routes/beatmaps');

const mapper_statsRoutes = require('./routes/mapper_stats');

const artist_statsRoutes = require('./routes/artist_stats');

const game_sessionsRoutes = require('./routes/game_sessions');

const game_roundsRoutes = require('./routes/game_rounds');

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

const daily_seedsRoutes = require('./routes/daily_seeds');

const server_cachesRoutes = require('./routes/server_caches');
const gameplayRoutes = require('./routes/gameplay');


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: "Osu Higher Lower",
        description: "Osu Higher Lower 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/osu_api_credentials', passport.authenticate('jwt', {session: false}), osu_api_credentialsRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

app.use('/api/server_caches', passport.authenticate('jwt', {session: false}), server_cachesRoutes);
app.use('/api/gameplay', passport.authenticate('jwt', {session: false}), gameplayRoutes);

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;
