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



const usersRoutes = require('./routes/users');

const rolesRoutes = require('./routes/roles');

const permissionsRoutes = require('./routes/permissions');

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

const standardsRoutes = require('./routes/standards');

const clausesRoutes = require('./routes/clauses');

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

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

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

const change_requestsRoutes = require('./routes/change_requests');

const approval_workflowsRoutes = require('./routes/approval_workflows');

const approval_stepsRoutes = require('./routes/approval_steps');

const approval_tasksRoutes = require('./routes/approval_tasks');

const esignature_eventsRoutes = require('./routes/esignature_events');

const training_coursesRoutes = require('./routes/training_courses');

const training_assignmentsRoutes = require('./routes/training_assignments');

const productsRoutes = require('./routes/products');

const suppliersRoutes = require('./routes/suppliers');

const batchesRoutes = require('./routes/batches');

const certificates_of_analysisRoutes = require('./routes/certificates_of_analysis');

const device_master_recordsRoutes = require('./routes/device_master_records');

const risk_assessmentsRoutes = require('./routes/risk_assessments');

const risk_itemsRoutes = require('./routes/risk_items');

const capasRoutes = require('./routes/capas');

const nonconformancesRoutes = require('./routes/nonconformances');

const complaintsRoutes = require('./routes/complaints');

const auditsRoutes = require('./routes/audits');

const audit_findingsRoutes = require('./routes/audit_findings');

const management_reviewsRoutes = require('./routes/management_reviews');

const regulatory_submissionsRoutes = require('./routes/regulatory_submissions');

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: "ISO13485 QMS Manager",
        description: "ISO13485 QMS Manager 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/document_types', passport.authenticate('jwt', {session: false}), document_typesRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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);

  
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;
