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

const postsRoutes = require('./routes/posts');

const post_commentsRoutes = require('./routes/post_comments');

const post_reactionsRoutes = require('./routes/post_reactions');

const post_savesRoutes = require('./routes/post_saves');

const save_collectionsRoutes = require('./routes/save_collections');

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

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

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

const story_viewsRoutes = require('./routes/story_views');

const highlightsRoutes = require('./routes/highlights');

const highlight_itemsRoutes = require('./routes/highlight_items');

const reelsRoutes = require('./routes/reels');

const reel_reactionsRoutes = require('./routes/reel_reactions');

const reel_commentsRoutes = require('./routes/reel_comments');

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

const conversation_membersRoutes = require('./routes/conversation_members');

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

const callsRoutes = require('./routes/calls');

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

const reportsRoutes = require('./routes/reports');

const productsRoutes = require('./routes/products');

const insight_snapshotsRoutes = require('./routes/insight_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: "Ultra Sosyal",
        description: "Ultra Sosyal 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/user_relationships', passport.authenticate('jwt', {session: false}), user_relationshipsRoutes);

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

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

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

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

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

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/stories', passport.authenticate('jwt', {session: false}), storiesRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

app.use('/api/insight_snapshots', passport.authenticate('jwt', {session: false}), insight_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);

  
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;
