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

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

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

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

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

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

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

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

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

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

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

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

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

const expensesRoutes = require('./routes/expenses');

const cash_movementsRoutes = require('./routes/cash_movements');

const poultry_lotsRoutes = require('./routes/poultry_lots');

const egg_collectionsRoutes = require('./routes/egg_collections');

const treatmentsRoutes = require('./routes/treatments');

const alertsRoutes = require('./routes/alerts');

const settingsRoutes = require('./routes/settings');

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: "YAYE MATY AGRO ERP",
        description: "YAYE MATY AGRO 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/role_permissions', passport.authenticate('jwt', {session: false}), role_permissionsRoutes);

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

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

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

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

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

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

app.use('/api/sale_items', passport.authenticate('jwt', {session: false}), sale_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/expenses', passport.authenticate('jwt', {session: false}), expensesRoutes);

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

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

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

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

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

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

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;
