
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 config = require('./config');
const swaggerUI = require('swagger-ui-express');
const swaggerJsDoc = require('swagger-jsdoc');
const { initializeRequestContext, attachAuthenticatedRequestContext } = require('./requestContext');

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

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

const servicesRoutes = require('./routes/services');

const companiesRoutes = require('./routes/companies');

const contactsRoutes = require('./routes/contacts');

const tagsRoutes = require('./routes/tags');

const pipelinesRoutes = require('./routes/pipelines');

const deal_stagesRoutes = require('./routes/deal_stages');

const leadsRoutes = require('./routes/leads');

const dealsRoutes = require('./routes/deals');

const project_templatesRoutes = require('./routes/project_templates');

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

const milestonesRoutes = require('./routes/milestones');

const tasksRoutes = require('./routes/tasks');

const task_dependenciesRoutes = require('./routes/task_dependencies');

const deliverablesRoutes = require('./routes/deliverables');

const project_risksRoutes = require('./routes/project_risks');

const project_status_reportsRoutes = require('./routes/project_status_reports');

const skillsRoutes = require('./routes/skills');

const team_membersRoutes = require('./routes/team_members');

const team_member_skillsRoutes = require('./routes/team_member_skills');

const resource_allocationsRoutes = require('./routes/resource_allocations');

const leave_requestsRoutes = require('./routes/leave_requests');

const public_holidaysRoutes = require('./routes/public_holidays');

const timesheetsRoutes = require('./routes/timesheets');

const time_entriesRoutes = require('./routes/time_entries');

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

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

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

const invoice_line_itemsRoutes = require('./routes/invoice_line_items');

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

const support_slasRoutes = require('./routes/support_slas');

const support_ticketsRoutes = require('./routes/support_tickets');

const ticket_commentsRoutes = require('./routes/ticket_comments');

const csat_surveysRoutes = require('./routes/csat_surveys');

const email_templatesRoutes = require('./routes/email_templates');

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

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

const importsRoutes = require('./routes/imports');


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: "TSC FleetOS",
        description: "TSC FleetOS 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(initializeRequestContext);

app.use('/api/auth', authRoutes);
app.use('/api/file', fileRoutes);
app.use('/api/pexels', pexelsRoutes);
app.use('/api/contact-form', contactFormRoutes);
app.use('/api/org-for-auth', organizationForAuthRoutes);
app.enable('trust proxy');

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

app.use('/api/users', usersRoutes);
app.use('/api/roles', rolesRoutes);
app.use('/api/permissions', permissionsRoutes);
app.use('/api/organizations', organizationsRoutes);
app.use('/api/tenants', tenantsRoutes);
app.use('/api/service_lines', service_linesRoutes);
app.use('/api/services', servicesRoutes);
app.use('/api/companies', companiesRoutes);
app.use('/api/contacts', contactsRoutes);
app.use('/api/tags', tagsRoutes);
app.use('/api/pipelines', pipelinesRoutes);
app.use('/api/deal_stages', deal_stagesRoutes);
app.use('/api/leads', leadsRoutes);
app.use('/api/deals', dealsRoutes);
app.use('/api/project_templates', project_templatesRoutes);
app.use('/api/projects', projectsRoutes);
app.use('/api/milestones', milestonesRoutes);
app.use('/api/tasks', tasksRoutes);
app.use('/api/task_dependencies', task_dependenciesRoutes);
app.use('/api/deliverables', deliverablesRoutes);
app.use('/api/project_risks', project_risksRoutes);
app.use('/api/project_status_reports', project_status_reportsRoutes);
app.use('/api/skills', skillsRoutes);
app.use('/api/team_members', team_membersRoutes);
app.use('/api/team_member_skills', team_member_skillsRoutes);
app.use('/api/resource_allocations', resource_allocationsRoutes);
app.use('/api/leave_requests', leave_requestsRoutes);
app.use('/api/public_holidays', public_holidaysRoutes);
app.use('/api/timesheets', timesheetsRoutes);
app.use('/api/time_entries', time_entriesRoutes);
app.use('/api/products', productsRoutes);
app.use('/api/contracts', contractsRoutes);
app.use('/api/invoices', invoicesRoutes);
app.use('/api/invoice_line_items', invoice_line_itemsRoutes);
app.use('/api/payments', paymentsRoutes);
app.use('/api/support_slas', support_slasRoutes);
app.use('/api/support_tickets', support_ticketsRoutes);
app.use('/api/ticket_comments', ticket_commentsRoutes);
app.use('/api/csat_surveys', csat_surveysRoutes);
app.use('/api/email_templates', email_templatesRoutes);
app.use('/api/notifications', notificationsRoutes);
app.use('/api/audit_logs', audit_logsRoutes);
app.use('/api/imports', importsRoutes);
app.use('/api/openai', openaiRoutes);
app.use('/api/ai', openaiRoutes);
app.use('/api/search', searchRoutes);
app.use('/api/sql', 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;
