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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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;
