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

const gdpr_consentsRoutes = require('./routes/gdpr_consents');

const gdpr_requestsRoutes = require('./routes/gdpr_requests');

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

const hotelsRoutes = require('./routes/hotels');

const room_typesRoutes = require('./routes/room_types');

const roomsRoutes = require('./routes/rooms');

const amenitiesRoutes = require('./routes/amenities');

const room_featuresRoutes = require('./routes/room_features');

const rate_plansRoutes = require('./routes/rate_plans');

const seasonal_ratesRoutes = require('./routes/seasonal_rates');

const inventory_blocksRoutes = require('./routes/inventory_blocks');

const guestsRoutes = require('./routes/guests');

const bookingsRoutes = require('./routes/bookings');

const booking_guestsRoutes = require('./routes/booking_guests');

const paymentsRoutes = require('./routes/payments');

const invoicesRoutes = require('./routes/invoices');

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

const promo_codesRoutes = require('./routes/promo_codes');

const booking_discountsRoutes = require('./routes/booking_discounts');

const housekeeping_tasksRoutes = require('./routes/housekeeping_tasks');

const service_requestsRoutes = require('./routes/service_requests');

const content_pagesRoutes = require('./routes/content_pages');

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: "Hotel Booking System",
        description: "Hotel Booking 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/languages', passport.authenticate('jwt', {session: false}), languagesRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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;

  app.listen(PORT, () => {
    console.log(`Listening on port ${PORT}`);
  });

module.exports = app;
