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

const job_positionsRoutes = require('./routes/job_positions');

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

const employee_contractsRoutes = require('./routes/employee_contracts');

const attendance_logsRoutes = require('./routes/attendance_logs');

const attendance_requestsRoutes = require('./routes/attendance_requests');

const overtime_logsRoutes = require('./routes/overtime_logs');

const disciplinary_actionsRoutes = require('./routes/disciplinary_actions');

const kpi_periodsRoutes = require('./routes/kpi_periods');

const kpi_scoresRoutes = require('./routes/kpi_scores');

const outlet_revenuesRoutes = require('./routes/outlet_revenues');

const service_charge_poolsRoutes = require('./routes/service_charge_pools');

const loan_accountsRoutes = require('./routes/loan_accounts');

const payroll_periodsRoutes = require('./routes/payroll_periods');

const payroll_itemsRoutes = require('./routes/payroll_items');

const payroll_adjustmentsRoutes = require('./routes/payroll_adjustments');

const payslipsRoutes = require('./routes/payslips');

const notification_messagesRoutes = require('./routes/notification_messages');

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: "HRIS FnB Multi Cabang",
        description: "HRIS FnB Multi Cabang 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/outlets', passport.authenticate('jwt', {session: false}), outletsRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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;
