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

const workspace_membershipsRoutes = require('./routes/workspace_memberships');

const data_connectionsRoutes = require('./routes/data_connections');

const financial_accountsRoutes = require('./routes/financial_accounts');

const vendorsRoutes = require('./routes/vendors');

const customersRoutes = require('./routes/customers');

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

const budgetsRoutes = require('./routes/budgets');

const budget_linesRoutes = require('./routes/budget_lines');

const forecastsRoutes = require('./routes/forecasts');

const forecast_scenariosRoutes = require('./routes/forecast_scenarios');

const metrics_snapshotsRoutes = require('./routes/metrics_snapshots');

const anomaliesRoutes = require('./routes/anomalies');

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

const recommendationsRoutes = require('./routes/recommendations');

const chat_threadsRoutes = require('./routes/chat_threads');

const chat_messagesRoutes = require('./routes/chat_messages');

const message_citationsRoutes = require('./routes/message_citations');

const files_libraryRoutes = require('./routes/files_library');

const sync_jobsRoutes = require('./routes/sync_jobs');


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: "CFO.ai",
        description: "CFO.ai 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/workspaces', passport.authenticate('jwt', {session: false}), workspacesRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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;
