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

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

const role_permissionsRoutes = require('./routes/role_permissions');

const approval_workflowsRoutes = require('./routes/approval_workflows');

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

const approvalsRoutes = require('./routes/approvals');

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

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

const fiscal_yearsRoutes = require('./routes/fiscal_years');

const funding_sourcesRoutes = require('./routes/funding_sources');

const budget_programsRoutes = require('./routes/budget_programs');

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

const allocationsRoutes = require('./routes/allocations');

const budget_reallocationsRoutes = require('./routes/budget_reallocations');

const procurement_plansRoutes = require('./routes/procurement_plans');

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

const tendersRoutes = require('./routes/tenders');

const vendorsRoutes = require('./routes/vendors');

const vendor_compliance_documentsRoutes = require('./routes/vendor_compliance_documents');

const bidsRoutes = require('./routes/bids');

const bid_evaluationsRoutes = require('./routes/bid_evaluations');

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

const programsRoutes = require('./routes/programs');

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

const project_milestonesRoutes = require('./routes/project_milestones');

const risksRoutes = require('./routes/risks');

const issuesRoutes = require('./routes/issues');

const field_verificationsRoutes = require('./routes/field_verifications');

const contractsRoutes = require('./routes/contracts');

const contract_amendmentsRoutes = require('./routes/contract_amendments');

const contract_milestonesRoutes = require('./routes/contract_milestones');

const grantsRoutes = require('./routes/grants');

const beneficiariesRoutes = require('./routes/beneficiaries');

const grant_applicationsRoutes = require('./routes/grant_applications');

const grant_evaluationsRoutes = require('./routes/grant_evaluations');

const grant_tranchesRoutes = require('./routes/grant_tranches');

const expense_categoriesRoutes = require('./routes/expense_categories');

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

const payment_requestsRoutes = require('./routes/payment_requests');

const payment_batchesRoutes = require('./routes/payment_batches');

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

const obligationsRoutes = require('./routes/obligations');

const ledger_entriesRoutes = require('./routes/ledger_entries');

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

const compliance_alertsRoutes = require('./routes/compliance_alerts');

const executive_summaryRoutes = require('./routes/executive_summary');


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

app.use('/api/executive-summary', passport.authenticate('jwt', {session: false}), executive_summaryRoutes);

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;
