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

const departmentsRoutes = require('./routes/departments');

const projectsRoutes = require('./routes/projects');

const budget_linesRoutes = require('./routes/budget_lines');

const workflow_rulesRoutes = require('./routes/workflow_rules');

const currency_ratesRoutes = require('./routes/currency_rates');

const requisitionsRoutes = require('./routes/requisitions');

const approval_stepsRoutes = require('./routes/approval_steps');

const procurement_casesRoutes = require('./routes/procurement_cases');

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

const supplier_categoriesRoutes = require('./routes/supplier_categories');

const supplier_diligence_checksRoutes = require('./routes/supplier_diligence_checks');

const tender_eventsRoutes = require('./routes/tender_events');

const supplier_offersRoutes = require('./routes/supplier_offers');

const bid_criteriaRoutes = require('./routes/bid_criteria');

const offer_scoresRoutes = require('./routes/offer_scores');

const awardsRoutes = require('./routes/awards');

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

const po_linesRoutes = require('./routes/po_lines');

const goods_receipt_notesRoutes = require('./routes/goods_receipt_notes');

const grn_linesRoutes = require('./routes/grn_lines');

const service_acceptance_notesRoutes = require('./routes/service_acceptance_notes');

const discrepancy_casesRoutes = require('./routes/discrepancy_cases');

const archive_itemsRoutes = require('./routes/archive_items');

const access_logsRoutes = require('./routes/access_logs');

const notificationsRoutes = require('./routes/notifications');

const audit_eventsRoutes = require('./routes/audit_events');

const export_jobsRoutes = require('./routes/export_jobs');

const sessionsRoutes = require('./routes/sessions');


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: "WWF-DRC ProcureFlow v2",
        description: "WWF-DRC ProcureFlow v2 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/tenants', passport.authenticate('jwt', {session: false}), tenantsRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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;

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

module.exports = app;
