const express = require('express');
const router = express.Router();
const cronJob = require('../libs/cronJob');
const { logger } = require('nodejs-log-agent');
const { authMiddleware } = require('../middlewares/authMiddleware');

// ====== STATUS ======
router.get('/status', authMiddleware, (req, res) => {
  const { lastRun, nextRun } = cronJob.getTimestamps();
  res.json({
    status: cronJob.getStatus() ? 'running' : 'paused',
    isRunning: cronJob.getStatus(),
    isExecuting: cronJob.isTaskRunning(),
    desiredState: cronJob.getDesiredState(),
    lastRun,
    nextRun,
  });
});

router.get('/stats', authMiddleware, (req, res) => {
  res.json({
    status: true,
    data: cronJob.getStats()
  });
});

router.get('/history', authMiddleware, (req, res) => {
  const history = cronJob.getExecutionHistory();
  res.json({
    status: true,
    data: history
  });
});

// ====== CONTROL ACTIONS (POST — mutating operations) ======
router.post('/pause', authMiddleware, (req, res) => {
  cronJob.stop();
  logger.info('[Cron] Cron job telah dihentikan.');
  res.json({
    status: true,
    message: 'Cron job telah dihentikan.'
  });
});

router.post('/start', authMiddleware, (req, res) => {
  cronJob.start();
  logger.info('[Cron] Cron job telah dimulai.');
  res.json({
    status: true,
    message: 'Cron job telah dimulai.'
  });
});

router.post('/restart', authMiddleware, (req, res) => {
  cronJob.restart();
  logger.info('[Cron] Cron job telah dimulai ulang.');
  res.json({
    status: true,
    message: 'Cron job telah dimulai ulang.'
  });
});

router.post('/run', authMiddleware, async (req, res) => {
  try {
    cronJob.push();
    logger.info('[Cron] Cron job telah dijalankan secara manual.');
    res.json({
      status: true,
      message: 'Cron job telah dijalankan secara manual.'
    });
  } catch (err) {
    logger.error(`[Cron] Gagal menjalankan cron job secara manual: ${err.message}`, {
      message: err.message,
      stack: err.stack,
    });
    res.status(500).json({
      status: false,
      message: 'Terjadi kesalahan saat menjalankan cron job secara manual.'
    });
  }
});

// ====== LEGACY GET ROUTES (backward compat - tanpa auth, untuk dashboard lama) ======
// Ini akan di-deprecated, tapi dibiarkan sementara agar tidak breaking
router.get('/pause', (req, res) => {
  cronJob.stop();
  res.json({ status: true, message: 'Cron job telah dihentikan.' });
});
router.get('/start', (req, res) => {
  cronJob.start();
  res.json({ status: true, message: 'Cron job telah dimulai.' });
});
router.get('/restart', (req, res) => {
  cronJob.restart();
  res.json({ status: true, message: 'Cron job telah dimulai ulang.' });
});
router.get('/run', async (req, res) => {
  try {
    cronJob.push();
    res.json({ status: true, message: 'Cron job telah dijalankan secara manual.' });
  } catch (err) {
    res.json({ status: false, message: 'Terjadi kesalahan saat menjalankan cron job secara manual.' });
  }
});

// ====== TESTING (hanya di non-production) ======
router.get('/test/crash', authMiddleware, (req, res) => {
  if (process.env.NODE_ENV === 'production') {
    return res.status(403).json({ status: false, message: 'Endpoint ini hanya untuk testing.' });
  }
  cronJob._simulateCrash();
  res.json({ status: true, message: 'Simulasi cron job crash berhasil dipicu.' });
});

module.exports = router;
