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



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

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

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

const organizationsRoutes = require('./routes/organizations');

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

const departmentsRoutes = require('./routes/departments');

const staff_profilesRoutes = require('./routes/staff_profiles');

const shiftsRoutes = require('./routes/shifts');

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

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

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

const guest_documentsRoutes = require('./routes/guest_documents');

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

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

const dynamic_pricing_rulesRoutes = require('./routes/dynamic_pricing_rules');

const sales_channelsRoutes = require('./routes/sales_channels');

const ota_connectionsRoutes = require('./routes/ota_connections');

const reservationsRoutes = require('./routes/reservations');

const reservation_guestsRoutes = require('./routes/reservation_guests');

const stay_foliosRoutes = require('./routes/stay_folios');

const folio_itemsRoutes = require('./routes/folio_items');

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

const refundsRoutes = require('./routes/refunds');

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

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

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

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

const booking_widgetsRoutes = require('./routes/booking_widgets');

const subscriptionsRoutes = require('./routes/subscriptions');

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

const daily_snapshotsRoutes = require('./routes/daily_snapshots');


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 Preview",
        description: "App Preview 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('/api/stripe/webhook', stripeRoutes.webhookRouter);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

app.use('/api/stripe', passport.authenticate('jwt', {session: false}), stripeRoutes.checkoutRouter);

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;
