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

const work_centersRoutes = require('./routes/work_centers');

const machinesRoutes = require('./routes/machines');

const maintenance_work_ordersRoutes = require('./routes/maintenance_work_orders');

const downtime_eventsRoutes = require('./routes/downtime_events');

const uomsRoutes = require('./routes/uoms');

const item_categoriesRoutes = require('./routes/item_categories');

const itemsRoutes = require('./routes/items');

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

const locationsRoutes = require('./routes/locations');

const inventory_lotsRoutes = require('./routes/inventory_lots');

const inventory_balancesRoutes = require('./routes/inventory_balances');

const inventory_transactionsRoutes = require('./routes/inventory_transactions');

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

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

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

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

const receiptsRoutes = require('./routes/receipts');

const receipt_linesRoutes = require('./routes/receipt_lines');

const bomsRoutes = require('./routes/boms');

const bom_linesRoutes = require('./routes/bom_lines');

const routingsRoutes = require('./routes/routings');

const routing_operationsRoutes = require('./routes/routing_operations');

const production_ordersRoutes = require('./routes/production_orders');

const production_operationsRoutes = require('./routes/production_operations');

const production_materialsRoutes = require('./routes/production_materials');

const production_outputsRoutes = require('./routes/production_outputs');

const qa_plansRoutes = require('./routes/qa_plans');

const qa_characteristicsRoutes = require('./routes/qa_characteristics');

const qa_inspectionsRoutes = require('./routes/qa_inspections');

const qa_resultsRoutes = require('./routes/qa_results');

const nonconformancesRoutes = require('./routes/nonconformances');

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

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

const gl_accountsRoutes = require('./routes/gl_accounts');

const journal_entriesRoutes = require('./routes/journal_entries');

const journal_linesRoutes = require('./routes/journal_lines');

const cost_centersRoutes = require('./routes/cost_centers');

const item_costsRoutes = require('./routes/item_costs');


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: "Manufacturing ERP",
        description: "Manufacturing 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/plants', passport.authenticate('jwt', {session: false}), plantsRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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;
