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

const role_assignmentsRoutes = require('./routes/role_assignments');

const payersRoutes = require('./routes/payers');

const payer_plansRoutes = require('./routes/payer_plans');

const procedure_familiesRoutes = require('./routes/procedure_families');

const cpt_codesRoutes = require('./routes/cpt_codes');

const patientsRoutes = require('./routes/patients');

const authorization_casesRoutes = require('./routes/authorization_cases');

const case_documentsRoutes = require('./routes/case_documents');

const submissionsRoutes = require('./routes/submissions');

const submission_eventsRoutes = require('./routes/submission_events');

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

const denialsRoutes = require('./routes/denials');

const appealsRoutes = require('./routes/appeals');

const templatesRoutes = require('./routes/templates');

const payer_rulesRoutes = require('./routes/payer_rules');

const rule_requirementsRoutes = require('./routes/rule_requirements');

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

const ai_outputsRoutes = require('./routes/ai_outputs');

const review_actionsRoutes = require('./routes/review_actions');

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

const integration_endpointsRoutes = require('./routes/integration_endpoints');

const contactsRoutes = require('./routes/contacts');


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: "Imaging PA & Denial Recovery",
        description: "Imaging PA & Denial Recovery 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/locations', passport.authenticate('jwt', {session: false}), locationsRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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;
