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

const openaiRoutes = require('./routes/openai');



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

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

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

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

const tenantsRoutes = require('./routes/tenants');

const role_assignmentsRoutes = require('./routes/role_assignments');

const organization_membershipsRoutes = require('./routes/organization_memberships');

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

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

const unit_typesRoutes = require('./routes/unit_types');

const unitsRoutes = require('./routes/units');

const unit_availability_blocksRoutes = require('./routes/unit_availability_blocks');

const negotiated_ratesRoutes = require('./routes/negotiated_rates');

const booking_requestsRoutes = require('./routes/booking_requests');

const booking_request_travelersRoutes = require('./routes/booking_request_travelers');

const approval_stepsRoutes = require('./routes/approval_steps');

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

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

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

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

const invoice_line_itemsRoutes = require('./routes/invoice_line_items');

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

const documentsRoutes = require('./routes/documents');

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

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

const activity_commentsRoutes = require('./routes/activity_comments');

const checklistsRoutes = require('./routes/checklists');

const checklist_itemsRoutes = require('./routes/checklist_items');

const job_runsRoutes = require('./routes/job_runs');

const corporateStayPortalRoutes = require('./routes/corporate_stay_portal');


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: "Gracey Corporate Stay Portal",
        description: "Gracey Corporate Stay Portal 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/organizations', passport.authenticate('jwt', {session: false}), organizationsRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

app.use('/api/corporate-stay-portal', passport.authenticate('jwt', {session: false}), corporateStayPortalRoutes);

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;
