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

const city_doctorsRoutes = require('./routes/city_doctors');

const rural_doctorsRoutes = require('./routes/rural_doctors');

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

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

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

const inventory_updatesRoutes = require('./routes/inventory_updates');

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

const dispatch_itemsRoutes = require('./routes/dispatch_items');

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

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

const chat_threadsRoutes = require('./routes/chat_threads');

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

const notificationsRoutes = require('./routes/notifications');

const trucksRoutes = require('./routes/trucks');

const truck_tracking_eventsRoutes = require('./routes/truck_tracking_events');

const vaccination_remindersRoutes = require('./routes/vaccination_reminders');

const medicine_remindersRoutes = require('./routes/medicine_reminders');

const ai_chat_sessionsRoutes = require('./routes/ai_chat_sessions');

const ai_chat_messagesRoutes = require('./routes/ai_chat_messages');

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: "Swa-Jiva Health System",
        description: "Swa-Jiva Health System 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/admins', passport.authenticate('jwt', {session: false}), adminsRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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;
