/**
 * SSL Monitor Routes
 * REST API endpoints for SSL certificate monitoring.
 *
 * @module routes/ssl-monitor
 */

const express = require('express');
const { success, error: errorResponse, notFound } = require('../src/utils/responses');

/**
 * SSL Monitor route factory
 * @param {Object} deps - Explicit dependencies
 * @param {Object} deps.sslMonitor - SSLMonitor instance
 * @param {Function} deps.asyncHandler - Async route handler wrapper
 * @param {Function} deps.logError - Error logging function
 * @returns {express.Router}
 */
module.exports = function({ sslMonitor, asyncHandler, logError }) {
  const router = express.Router();

  /**
   * GET /ssl/certificates
   * Get all SSL certificate statuses
   */
  router.get('/certificates', asyncHandler(async (req, res) => {
    const status = sslMonitor.getStatus();
    success(res, { certificates: status });
  }, 'ssl-certificates'));

  /**
   * GET /ssl/certificates/:serviceId
   * Get SSL certificate status for a specific service
   */
  router.get('/certificates/:serviceId', asyncHandler(async (req, res) => {
    const { serviceId } = req.params;
    const certStatus = sslMonitor.getServiceCertStatus(serviceId);

    if (!certStatus) {
      return notFound(res, `No SSL certificate status found for service: ${serviceId}`);
    }

    success(res, { certificate: certStatus });
  }, 'ssl-certificate-service'));

  /**
   * POST /ssl/check
   * Trigger an on-demand check of all SSL certificates
   */
  router.post('/check', asyncHandler(async (req, res) => {
    const results = await sslMonitor.checkAll();
    success(res, { certificates: results, message: 'SSL check completed' });
  }, 'ssl-check-all'));

  /**
   * POST /ssl/check/:serviceId
   * Check the SSL certificate for a specific service
   */
  router.post('/check/:serviceId', asyncHandler(async (req, res) => {
    const { serviceId } = req.params;

    // Look up the existing cert status to find the hostname
    const existingCert = sslMonitor.getServiceCertStatus(serviceId);
    if (!existingCert) {
      return notFound(res, `No HTTPS URL found for service: ${serviceId}`);
    }

    try {
      const result = await sslMonitor.checkCert(existingCert.hostname, existingCert.port);
      success(res, { certificate: { ...result, serviceId } });
    } catch (err) {
      errorResponse(res, `Failed to check SSL certificate: ${err.message}`, 500);
    }
  }, 'ssl-check-service'));

  /**
   * GET /ssl/config
   * Get current SSL monitoring configuration
   */
  router.get('/config', asyncHandler(async (req, res) => {
    const config = sslMonitor.getConfig();
    success(res, { config });
  }, 'ssl-config-get'));

  /**
   * POST /ssl/config
   * Update SSL monitoring configuration
   * Body: { enabled: boolean, intervalMs: number }
   */
  router.post('/config', asyncHandler(async (req, res) => {
    const { enabled, intervalMs } = req.body;

    // Validate inputs
    if (enabled !== undefined && typeof enabled !== 'boolean') {
      return errorResponse(res, 'enabled must be a boolean', 400);
    }
    if (intervalMs !== undefined) {
      if (typeof intervalMs !== 'number' || intervalMs < 60000) {
        return errorResponse(res, 'intervalMs must be a number >= 60000 (1 minute)', 400);
      }
    }

    const updates = {};
    if (enabled !== undefined) updates.enabled = enabled;
    if (intervalMs !== undefined) updates.intervalMs = intervalMs;

    sslMonitor.updateConfig(updates);
    const config = sslMonitor.getConfig();
    success(res, { config, message: 'SSL monitoring config updated' });
  }, 'ssl-config-update'));

  return router;
};
