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

const organizationForAuthRoutes = require('./routes/organizationLogin');

const openaiRoutes = require('./routes/openai');

const contactFormRoutes = require('./routes/contactForm');

const usersRoutes = require('./routes/users');

const app_accountsRoutes = require('./routes/app_accounts');

const applicationsRoutes = require('./routes/applications');

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

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

const benefit_plansRoutes = require('./routes/benefit_plans');

const billsRoutes = require('./routes/bills');

const candidatesRoutes = require('./routes/candidates');

const cardsRoutes = require('./routes/cards');

const compensationsRoutes = require('./routes/compensations');

const deductionsRoutes = require('./routes/deductions');

const devicesRoutes = require('./routes/devices');

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

const earningsRoutes = require('./routes/earnings');

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

const employmentsRoutes = require('./routes/employments');

const enrollment_learningsRoutes = require('./routes/enrollment_learnings');

const enrollmentsRoutes = require('./routes/enrollments');

const expense_linesRoutes = require('./routes/expense_lines');

const expense_reportsRoutes = require('./routes/expense_reports');

const goalsRoutes = require('./routes/goals');

const identity_accountsRoutes = require('./routes/identity_accounts');

const interviewsRoutes = require('./routes/interviews');

const inventory_eventsRoutes = require('./routes/inventory_events');

const job_requisitionsRoutes = require('./routes/job_requisitions');

const learning_coursesRoutes = require('./routes/learning_courses');

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

const offersRoutes = require('./routes/offers');

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

const payroll_runsRoutes = require('./routes/payroll_runs');

const policiesRoutes = require('./routes/policies');

const positionsRoutes = require('./routes/positions');

const review_cyclesRoutes = require('./routes/review_cycles');

const reviewsRoutes = require('./routes/reviews');

const schedule_shiftsRoutes = require('./routes/schedule_shifts');

const taxesRoutes = require('./routes/taxes');

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

const timecardsRoutes = require('./routes/timecards');

const travel_bookingsRoutes = require('./routes/travel_bookings');

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

const rolesRoutes = require('./routes/roles');

const permissionsRoutes = require('./routes/permissions');

const organizationsRoutes = require('./routes/organizations');

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: 'CTPLERP',
      description:
        'CTPLERP 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/app_accounts',
  passport.authenticate('jwt', { session: false }),
  app_accountsRoutes,
);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

app.use('/api/contact-form', contactFormRoutes);

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

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;

db.sequelize.sync().then(function () {
  app.listen(PORT, () => {
    console.log(`Listening on port ${PORT}`);
  });
});

module.exports = app;
