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

const productsRoutes = require('./routes/products');

const brandsRoutes = require('./routes/brands');

const categoriesRoutes = require('./routes/categories');

const customersRoutes = require('./routes/customers');

const price_listsRoutes = require('./routes/price_lists');

const price_list_itemsRoutes = require('./routes/price_list_items');

const discountsRoutes = require('./routes/discounts');

const registersRoutes = require('./routes/registers');

const cash_drawer_sessionsRoutes = require('./routes/cash_drawer_sessions');

const salesRoutes = require('./routes/sales');

const sale_itemsRoutes = require('./routes/sale_items');

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

const returnsRoutes = require('./routes/returns');

const return_itemsRoutes = require('./routes/return_items');

const suppliersRoutes = require('./routes/suppliers');

const purchase_ordersRoutes = require('./routes/purchase_orders');

const purchase_order_itemsRoutes = require('./routes/purchase_order_items');

const inventory_itemsRoutes = require('./routes/inventory_items');

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

const stock_transfersRoutes = require('./routes/stock_transfers');

const stock_transfer_itemsRoutes = require('./routes/stock_transfer_items');


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: "UAE Retail POS",
        description: "UAE Retail POS 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/stores', passport.authenticate('jwt', {session: false}), storesRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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;
