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

const company_membershipsRoutes = require('./routes/company_memberships');

const branchesRoutes = require('./routes/branches');

const departmentsRoutes = require('./routes/departments');

const compliance_categoriesRoutes = require('./routes/compliance_categories');

const compliance_templatesRoutes = require('./routes/compliance_templates');

const company_compliancesRoutes = require('./routes/company_compliances');

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

const documentsRoutes = require('./routes/documents');

const document_versionsRoutes = require('./routes/document_versions');

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

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

const subscription_plansRoutes = require('./routes/subscription_plans');

const company_subscriptionsRoutes = require('./routes/company_subscriptions');

const paymentsRoutes = require('./routes/payments');

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

const ai_chat_messagesRoutes = require('./routes/ai_chat_messages');

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

const activity_eventsRoutes = require('./routes/activity_events');

const report_exportsRoutes = require('./routes/report_exports');

const compliance_rule_overridesRoutes = require('./routes/compliance_rule_overrides');

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

const notifications_preferencesRoutes = require('./routes/notifications_preferences');


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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;
