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

const oauth_accountsRoutes = require('./routes/oauth_accounts');

const integrationsRoutes = require('./routes/integrations');

const user_storiesRoutes = require('./routes/user_stories');

const acceptance_criteriaRoutes = require('./routes/acceptance_criteria');

const documentsRoutes = require('./routes/documents');

const document_foldersRoutes = require('./routes/document_folders');

const document_versionsRoutes = require('./routes/document_versions');

const story_document_linksRoutes = require('./routes/story_document_links');

const collaboration_sessionsRoutes = require('./routes/collaboration_sessions');

const comment_threadsRoutes = require('./routes/comment_threads');

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

const comment_reactionsRoutes = require('./routes/comment_reactions');

const mentionsRoutes = require('./routes/mentions');

const approval_workflowsRoutes = require('./routes/approval_workflows');

const approvalsRoutes = require('./routes/approvals');

const approval_reviewersRoutes = require('./routes/approval_reviewers');

const audit_eventsRoutes = require('./routes/audit_events');

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

const sprintsRoutes = require('./routes/sprints');

const sprint_itemsRoutes = require('./routes/sprint_items');

const blockersRoutes = require('./routes/blockers');

const activity_feed_itemsRoutes = require('./routes/activity_feed_items');

const ai_generationsRoutes = require('./routes/ai_generations');


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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;
