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

const market_symbolsRoutes = require('./routes/market_symbols');

const symbol_fundamentalsRoutes = require('./routes/symbol_fundamentals');

const price_quotesRoutes = require('./routes/price_quotes');

const technical_indicatorsRoutes = require('./routes/technical_indicators');

const analyst_ratingsRoutes = require('./routes/analyst_ratings');

const earnings_reportsRoutes = require('./routes/earnings_reports');

const news_articlesRoutes = require('./routes/news_articles');

const news_article_symbolsRoutes = require('./routes/news_article_symbols');

const article_bookmarksRoutes = require('./routes/article_bookmarks');

const watchlistsRoutes = require('./routes/watchlists');

const watchlist_itemsRoutes = require('./routes/watchlist_items');

const paper_accountsRoutes = require('./routes/paper_accounts');

const paper_ordersRoutes = require('./routes/paper_orders');

const paper_tradesRoutes = require('./routes/paper_trades');

const paper_positionsRoutes = require('./routes/paper_positions');

const portfolio_snapshotsRoutes = require('./routes/portfolio_snapshots');

const screener_filtersRoutes = require('./routes/screener_filters');

const screener_runsRoutes = require('./routes/screener_runs');

const screener_resultsRoutes = require('./routes/screener_results');

const ai_chat_sessionsRoutes = require('./routes/ai_chat_sessions');

const ai_messagesRoutes = require('./routes/ai_messages');

const learning_modulesRoutes = require('./routes/learning_modules');

const user_tooltipsRoutes = require('./routes/user_tooltips');

const ir_companiesRoutes = require('./routes/ir_companies');

const ir_management_membersRoutes = require('./routes/ir_management_members');

const ir_filingsRoutes = require('./routes/ir_filings');

const ir_dividendsRoutes = require('./routes/ir_dividends');

const ir_announcementsRoutes = require('./routes/ir_announcements');

const ir_financial_statement_summariesRoutes = require('./routes/ir_financial_statement_summaries');

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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;
