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

const contactFormRoutes = require('./routes/contactForm');

const usersRoutes = require('./routes/users');

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

const bedsRoutes = require('./routes/beds');

const booking_bedsRoutes = require('./routes/booking_beds');

const booking_upsellsRoutes = require('./routes/booking_upsells');

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

const couponsRoutes = require('./routes/coupons');

const event_ordersRoutes = require('./routes/event_orders');

const event_ticket_typesRoutes = require('./routes/event_ticket_types');

const event_ticketsRoutes = require('./routes/event_tickets');

const eventsRoutes = require('./routes/events');

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

const inventory_datesRoutes = require('./routes/inventory_dates');

const maintenance_ticketsRoutes = require('./routes/maintenance_tickets');

const message_threadsRoutes = require('./routes/message_threads');

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

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

const reviewsRoutes = require('./routes/reviews');

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

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

const upsellsRoutes = require('./routes/upsells');

const user_rolesRoutes = require('./routes/user_roles');

const rolesRoutes = require('./routes/roles');

const permissionsRoutes = require('./routes/permissions');

const propertiesRoutes = require('./routes/properties');

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: "Proximo",
        description: "Proximo 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.enable('trust proxy');

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

app.use('/api/contact-form', contactFormRoutes);

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

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;
