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

const assistant_profilesRoutes = require('./routes/assistant_profiles');

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

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

const voice_sessionsRoutes = require('./routes/voice_sessions');

const tool_providersRoutes = require('./routes/tool_providers');

const toolsRoutes = require('./routes/tools');

const tool_actionsRoutes = require('./routes/tool_actions');

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

const memory_itemsRoutes = require('./routes/memory_items');

const tasksRoutes = require('./routes/tasks');

const task_stepsRoutes = require('./routes/task_steps');

const tool_runsRoutes = require('./routes/tool_runs');

const confirmationsRoutes = require('./routes/confirmations');

const meetingsRoutes = require('./routes/meetings');

const calendar_eventsRoutes = require('./routes/calendar_events');

const contactsRoutes = require('./routes/contacts');

const outbound_messagesRoutes = require('./routes/outbound_messages');

const travel_requestsRoutes = require('./routes/travel_requests');

const travel_bookingsRoutes = require('./routes/travel_bookings');

const payment_transactionsRoutes = require('./routes/payment_transactions');

const native_app_checksRoutes = require('./routes/native_app_checks');

const audit_logsRoutes = require('./routes/audit_logs');


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: "AI Assistant SaaS",
        description: "AI Assistant SaaS 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/user_settings', passport.authenticate('jwt', {session: false}), user_settingsRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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;
