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

const role_permissionsRoutes = require('./routes/role_permissions');

const addressesRoutes = require('./routes/addresses');

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

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

const payment_termsRoutes = require('./routes/payment_terms');

const taxesRoutes = require('./routes/taxes');

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

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

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

const warehousesRoutes = require('./routes/warehouses');

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

const inventory_movementsRoutes = require('./routes/inventory_movements');

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

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

const sales_ordersRoutes = require('./routes/sales_orders');

const sales_order_linesRoutes = require('./routes/sales_order_lines');

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

const purchase_order_linesRoutes = require('./routes/purchase_order_lines');

const goods_receiptsRoutes = require('./routes/goods_receipts');

const goods_receipt_linesRoutes = require('./routes/goods_receipt_lines');

const shipmentsRoutes = require('./routes/shipments');

const shipment_linesRoutes = require('./routes/shipment_lines');

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

const invoice_linesRoutes = require('./routes/invoice_lines');

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


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: "Multi-tenant ERP",
        description: "Multi-tenant ERP 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/organization_memberships', passport.authenticate('jwt', {session: false}), organization_membershipsRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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;

db.sequelize.sync().then(function () {
  app.listen(PORT, () => {
    console.log(`Listening on port ${PORT}`);
  });
});

module.exports = app;
