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

const guarantorsRoutes = require('./routes/guarantors');

const doctorsRoutes = require('./routes/doctors');

const visitsRoutes = require('./routes/visits');

const ordersRoutes = require('./routes/orders');

const radiology_typesRoutes = require('./routes/radiology_types');

const radiology_studiesRoutes = require('./routes/radiology_studies');

const ct_typesRoutes = require('./routes/ct_types');

const ct_studiesRoutes = require('./routes/ct_studies');

const lab_testsRoutes = require('./routes/lab_tests');

const lab_ordersRoutes = require('./routes/lab_orders');

const lab_resultsRoutes = require('./routes/lab_results');

const endoscopy_casesRoutes = require('./routes/endoscopy_cases');

const surgery_casesRoutes = require('./routes/surgery_cases');

const surgery_consumablesRoutes = require('./routes/surgery_consumables');

const anesthesia_recordsRoutes = require('./routes/anesthesia_records');

const cathlab_casesRoutes = require('./routes/cathlab_cases');

const ecg_stress_testsRoutes = require('./routes/ecg_stress_tests');

const nursing_staffRoutes = require('./routes/nursing_staff');

const cleaning_staffRoutes = require('./routes/cleaning_staff');

const inventory_consumablesRoutes = require('./routes/inventory_consumables');

const pharmacy_inventoryRoutes = require('./routes/pharmacy_inventory');

const pharmacy_sales_invoicesRoutes = require('./routes/pharmacy_sales_invoices');

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

const purchasesRoutes = require('./routes/purchases');

const patient_invoicesRoutes = require('./routes/patient_invoices');

const ledger_entriesRoutes = require('./routes/ledger_entries');

const journal_entriesRoutes = require('./routes/journal_entries');

const trial_balancesRoutes = require('./routes/trial_balances');

const closing_balancesRoutes = require('./routes/closing_balances');

const inpatient_roomsRoutes = require('./routes/inpatient_rooms');

const room_bookingsRoutes = require('./routes/room_bookings');

const restaurant_mealsRoutes = require('./routes/restaurant_meals');

const restaurant_inventoryRoutes = require('./routes/restaurant_inventory');

const maternity_casesRoutes = require('./routes/maternity_cases');

const pregnancy_followupsRoutes = require('./routes/pregnancy_followups');

const nicu_incubatorsRoutes = require('./routes/nicu_incubators');

const daily_followup_clinicRoutes = require('./routes/daily_followup_clinic');

const audit_logRoutes = require('./routes/audit_log');

const settingsRoutes = require('./routes/settings');


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: "App Draft",
        description: "App Draft 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/patients', passport.authenticate('jwt', {session: false}), patientsRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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;

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

module.exports = app;
