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

const tenant_membershipsRoutes = require('./routes/tenant_memberships');

const service_typesRoutes = require('./routes/service_types');

const authentication_methodsRoutes = require('./routes/authentication_methods');

const service_auth_policiesRoutes = require('./routes/service_auth_policies');

const document_categoriesRoutes = require('./routes/document_categories');

const document_typesRoutes = require('./routes/document_types');

const document_template_variablesRoutes = require('./routes/document_template_variables');

const document_templatesRoutes = require('./routes/document_templates');

const workflow_definitionsRoutes = require('./routes/workflow_definitions');

const workflow_stepsRoutes = require('./routes/workflow_steps');

const price_listsRoutes = require('./routes/price_lists');

const price_rulesRoutes = require('./routes/price_rules');

const locationsRoutes = require('./routes/locations');

const contract_foldersRoutes = require('./routes/contract_folders');

const contract_documentsRoutes = require('./routes/contract_documents');

const contract_data_fieldsRoutes = require('./routes/contract_data_fields');

const contract_participantsRoutes = require('./routes/contract_participants');

const participant_invitationsRoutes = require('./routes/participant_invitations');

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

const payment_sharesRoutes = require('./routes/payment_shares');

const authentication_sessionsRoutes = require('./routes/authentication_sessions');

const authentication_attemptsRoutes = require('./routes/authentication_attempts');

const id_verification_artifactsRoutes = require('./routes/id_verification_artifacts');

const bank_verificationsRoutes = require('./routes/bank_verifications');

const notification_recordsRoutes = require('./routes/notification_records');

const notification_record_itemsRoutes = require('./routes/notification_record_items');

const signing_actionsRoutes = require('./routes/signing_actions');

const document_revisionsRoutes = require('./routes/document_revisions');

const revision_approvalsRoutes = require('./routes/revision_approvals');

const revocation_requestsRoutes = require('./routes/revocation_requests');

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

const support_ticket_messagesRoutes = require('./routes/support_ticket_messages');

const ai_contract_classificationsRoutes = require('./routes/ai_contract_classifications');

const disallowed_contract_rulesRoutes = require('./routes/disallowed_contract_rules');

const service_suitability_rulesRoutes = require('./routes/service_suitability_rules');

const audit_eventsRoutes = require('./routes/audit_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: "Firma Electronica WF",
        description: "Firma Electronica WF 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/tenants', passport.authenticate('jwt', {session: false}), tenantsRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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