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

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

const user_rolesRoutes = require('./routes/user_roles');

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

const job_titlesRoutes = require('./routes/job_titles');

const work_locationsRoutes = require('./routes/work_locations');

const employeesRoutes = require('./routes/employees');

const employment_contractsRoutes = require('./routes/employment_contracts');

const leave_typesRoutes = require('./routes/leave_types');

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

const attendance_policiesRoutes = require('./routes/attendance_policies');

const work_schedulesRoutes = require('./routes/work_schedules');

const employee_schedule_assignmentsRoutes = require('./routes/employee_schedule_assignments');

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

const holidaysRoutes = require('./routes/holidays');

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

const expense_claimsRoutes = require('./routes/expense_claims');

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

const announcementsRoutes = require('./routes/announcements');

const api_configsRoutes = require('./routes/api_configs');

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: "App Preview",
        description: "App Preview 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/companies', passport.authenticate('jwt', {session: false}), companiesRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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);

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;
