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

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

const reactionsRoutes = require('./routes/reactions');

const storiesRoutes = require('./routes/stories');

const conversationsRoutes = require('./routes/conversations');

const messagesRoutes = require('./routes/messages');

const groupsRoutes = require('./routes/groups');

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

const ticketsRoutes = require('./routes/tickets');

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

const user_settingsRoutes = require('./routes/user_settings');

const followsRoutes = require('./routes/follows');

const hashtagsRoutes = require('./routes/hashtags');

const post_hashtagsRoutes = require('./routes/post_hashtags');

const media_assetsRoutes = require('./routes/media_assets');

const live_streamsRoutes = require('./routes/live_streams');

const transactionsRoutes = require('./routes/transactions');

const ai_recommendationsRoutes = require('./routes/ai_recommendations');

const content_moderation_reportsRoutes = require('./routes/content_moderation_reports');

const gamification_badgesRoutes = require('./routes/gamification_badges');

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


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: "Socio Social App",
        description: "Socio Social App 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/posts', passport.authenticate('jwt', {session: false}), postsRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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;

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

module.exports = app;
