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

const patient_profilesRoutes = require('./routes/patient_profiles');

const medical_campsRoutes = require('./routes/medical_camps');

const appointmentsRoutes = require('./routes/appointments');

const consultationsRoutes = require('./routes/consultations');

const medical_reportsRoutes = require('./routes/medical_reports');

const medicinesRoutes = require('./routes/medicines');

const inventory_itemsRoutes = require('./routes/inventory_items');

const prescriptionsRoutes = require('./routes/prescriptions');

const prescription_itemsRoutes = require('./routes/prescription_items');

const medicine_dispatchesRoutes = require('./routes/medicine_dispatches');

const vaccinationsRoutes = require('./routes/vaccinations');

const patient_vaccinationsRoutes = require('./routes/patient_vaccinations');

const remindersRoutes = require('./routes/reminders');

const chat_sessionsRoutes = require('./routes/chat_sessions');

const messagesRoutes = require('./routes/messages');

const video_callsRoutes = require('./routes/video_calls');

const chatbot_interactionsRoutes = require('./routes/chatbot_interactions');

const feedbacksRoutes = require('./routes/feedbacks');


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: "Swa-Jiva IRHMS",
        description: "Swa-Jiva IRHMS 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/doctor_profiles', passport.authenticate('jwt', {session: false}), doctor_profilesRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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;
