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

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

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

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

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

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

const approved_vendorsRoutes = require('./routes/approved_vendors');

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

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

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

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

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

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

const machine_eventsRoutes = require('./routes/machine_events');

const reason_codesRoutes = require('./routes/reason_codes');

const work_ordersRoutes = require('./routes/work_orders');

const work_order_operationsRoutes = require('./routes/work_order_operations');

const lotsRoutes = require('./routes/lots');

const serialsRoutes = require('./routes/serials');

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

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

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

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

const inspection_plansRoutes = require('./routes/inspection_plans');

const inspection_characteristicsRoutes = require('./routes/inspection_characteristics');

const inspectionsRoutes = require('./routes/inspections');

const inspection_resultsRoutes = require('./routes/inspection_results');

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

const disposition_codesRoutes = require('./routes/disposition_codes');

const capa_actionsRoutes = require('./routes/capa_actions');

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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;

  app.listen(PORT, () => {
    console.log(`Listening on port ${PORT}`);
  });

module.exports = app;
