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

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

const numbering_sequencesRoutes = require('./routes/numbering_sequences');

const clientsRoutes = require('./routes/clients');

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

const product_categoriesRoutes = require('./routes/product_categories');

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

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

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

const quotesRoutes = require('./routes/quotes');

const quote_itemsRoutes = require('./routes/quote_items');

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

const sales_order_itemsRoutes = require('./routes/sales_order_items');

const delivery_notesRoutes = require('./routes/delivery_notes');

const delivery_note_itemsRoutes = require('./routes/delivery_note_items');

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

const invoice_itemsRoutes = require('./routes/invoice_items');

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

const credit_notesRoutes = require('./routes/credit_notes');

const credit_note_itemsRoutes = require('./routes/credit_note_items');

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

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

const stock_receptionsRoutes = require('./routes/stock_receptions');

const stock_reception_itemsRoutes = require('./routes/stock_reception_items');

const stock_reservationsRoutes = require('./routes/stock_reservations');

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

const inventory_countsRoutes = require('./routes/inventory_counts');

const inventory_count_itemsRoutes = require('./routes/inventory_count_items');

const import_jobsRoutes = require('./routes/import_jobs');

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: "POLYNOVA ERP SaaS",
        description: "POLYNOVA ERP SaaS 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/tax_rates', passport.authenticate('jwt', {session: false}), tax_ratesRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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);

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;
