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

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

const saved_addressesRoutes = require('./routes/saved_addresses');

const service_packagesRoutes = require('./routes/service_packages');

const service_add_onsRoutes = require('./routes/service_add_ons');

const service_requestsRoutes = require('./routes/service_requests');

const service_request_add_onsRoutes = require('./routes/service_request_add_ons');

const request_checklist_itemsRoutes = require('./routes/request_checklist_items');

const request_timeline_eventsRoutes = require('./routes/request_timeline_events');

const request_documentsRoutes = require('./routes/request_documents');

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

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

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

const invoicesRoutes = require('./routes/invoices');

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

const legal_documentsRoutes = require('./routes/legal_documents');

const document_acceptancesRoutes = require('./routes/document_acceptances');

const support_ticketsRoutes = require('./routes/support_tickets');

const leadsRoutes = require('./routes/leads');

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

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

const webhook_endpointsRoutes = require('./routes/webhook_endpoints');

const webhook_deliveriesRoutes = require('./routes/webhook_deliveries');

const csv_jobsRoutes = require('./routes/csv_jobs');

const usage_eventsRoutes = require('./routes/usage_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: "Entangle Retrievals SaaS",
        description: "Entangle Retrievals 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/organization_invitations', passport.authenticate('jwt', {session: false}), organization_invitationsRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

app.use('/api/usage_events', passport.authenticate('jwt', {session: false}), usage_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);

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;

  app.listen(PORT, () => {
    console.log(`Listening on port ${PORT}`);
  });

module.exports = app;
