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

const subscriptionsRoutes = require('./routes/subscriptions');

const trading_accountsRoutes = require('./routes/trading_accounts');

const instrumentsRoutes = require('./routes/instruments');

const setupsRoutes = require('./routes/setups');

const tagsRoutes = require('./routes/tags');

const tradesRoutes = require('./routes/trades');

const trade_attachmentsRoutes = require('./routes/trade_attachments');

const trade_rulesRoutes = require('./routes/trade_rules');

const trade_rule_checksRoutes = require('./routes/trade_rule_checks');

const mood_entriesRoutes = require('./routes/mood_entries');

const goalsRoutes = require('./routes/goals');

const milestonesRoutes = require('./routes/milestones');

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

const economic_eventsRoutes = require('./routes/economic_events');

const csv_import_jobsRoutes = require('./routes/csv_import_jobs');

const csv_import_row_errorsRoutes = require('./routes/csv_import_row_errors');

const broker_connectionsRoutes = require('./routes/broker_connections');

const trade_sync_runsRoutes = require('./routes/trade_sync_runs');

const ai_insight_runsRoutes = require('./routes/ai_insight_runs');

const ai_insight_itemsRoutes = require('./routes/ai_insight_items');

const alert_rulesRoutes = require('./routes/alert_rules');

const alertsRoutes = require('./routes/alerts');

const dashboard_widgetsRoutes = require('./routes/dashboard_widgets');

const pdf_reportsRoutes = require('./routes/pdf_reports');


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: "Premium Trading Journal",
        description: "Premium Trading Journal 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/billing_customers', passport.authenticate('jwt', {session: false}), billing_customersRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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;
