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

const restaurantsRoutes = require('./routes/restaurants');

const restaurant_tablesRoutes = require('./routes/restaurant_tables');

const work_schedulesRoutes = require('./routes/work_schedules');

const work_shiftsRoutes = require('./routes/work_shifts');

const attendance_eventsRoutes = require('./routes/attendance_events');

const geofence_alertsRoutes = require('./routes/geofence_alerts');

const menu_categoriesRoutes = require('./routes/menu_categories');

const menu_itemsRoutes = require('./routes/menu_items');

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

const order_itemsRoutes = require('./routes/order_items');

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

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

const loyalty_accountsRoutes = require('./routes/loyalty_accounts');

const loyalty_rulesRoutes = require('./routes/loyalty_rules');

const loyalty_transactionsRoutes = require('./routes/loyalty_transactions');

const customer_reviewsRoutes = require('./routes/customer_reviews');

const notification_eventsRoutes = require('./routes/notification_events');

const stock_locationsRoutes = require('./routes/stock_locations');

const stock_itemsRoutes = require('./routes/stock_items');

const stock_movementsRoutes = require('./routes/stock_movements');

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

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


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: "TEXAS GRILLZ Suite",
        description: "TEXAS GRILLZ Suite 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/account_approvals', passport.authenticate('jwt', {session: false}), account_approvalsRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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;
