var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');

const corsOptions = require('./libs/cors');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
const templateRouter = require('./routes/template');
const cronRouter = require('./routes/cron');
const invoiceRouter = require('./routes/invoice');
const corsRouter = require('./routes/corsOrigin');
const logRouter = require('./routes/log');
const pdfRoutes = require('./routes/pdf');
const settingRoutes = require('./routes/setting');
const pkg = require('./package.json');

var app = express();
const { logger, heartbeatService, initializeProcessHandlers } = require('nodejs-log-agent');
app.locals.appVersion = pkg.version;
app.locals.apiDocsUrl = process.env.API_DOCS_URL || '#'; // Ambil dari .env, fallback ke '#'
// --- Inisialisasi Penanganan Error Global Aplikasi dan Graceful Shutdown ---
// Panggil fungsi inisialisasi dari modul observability
initializeProcessHandlers(logger, heartbeatService);

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.set('trust proxy', true);
app.use(express.static(path.join(__dirname, 'public')));
app.use(corsOptions);
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/cron', cronRouter);
app.use('/invoice', invoiceRouter);
app.use('/template', templateRouter);
app.use('/cors-origin', corsRouter);
app.use('/log', logRouter);
app.use('/pdf', pdfRoutes);
app.use('/setting', settingRoutes);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
