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

const feature_flagsRoutes = require('./routes/feature_flags');

const mattersRoutes = require('./routes/matters');

const matter_partiesRoutes = require('./routes/matter_parties');

const filesRoutes = require('./routes/files');

const file_extractionsRoutes = require('./routes/file_extractions');

const assistant_threadsRoutes = require('./routes/assistant_threads');

const assistant_messagesRoutes = require('./routes/assistant_messages');

const ai_jobsRoutes = require('./routes/ai_jobs');

const legal_templatesRoutes = require('./routes/legal_templates');

const template_fieldsRoutes = require('./routes/template_fields');

const generated_documentsRoutes = require('./routes/generated_documents');

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

const research_queriesRoutes = require('./routes/research_queries');

const legal_sourcesRoutes = require('./routes/legal_sources');

const research_resultsRoutes = require('./routes/research_results');

const citator_checksRoutes = require('./routes/citator_checks');

const mock_trialsRoutes = require('./routes/mock_trials');

const mock_trial_rolesRoutes = require('./routes/mock_trial_roles');

const mock_trial_turnsRoutes = require('./routes/mock_trial_turns');

const transcription_jobsRoutes = require('./routes/transcription_jobs');

const medical_chronology_reportsRoutes = require('./routes/medical_chronology_reports');

const medical_eventsRoutes = require('./routes/medical_events');

const causation_analysesRoutes = require('./routes/causation_analyses');

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: "Pro Se Litigant AI",
        description: "Pro Se Litigant AI 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/subscriptions', passport.authenticate('jwt', {session: false}), subscriptionsRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

app.use(
    '/api/openai',
    openaiRoutes,
);
app.use(
    '/api/ai',
    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;

db.sequelize.sync().then(function () {
  app.listen(PORT, () => {
    console.log(`Listening on port ${PORT}`);
  });
});

module.exports = app;