/**
 * Health Check Routes
 *
 * Endpoints for monitoring service health and readiness
 */

import { Router, Request, Response } from 'express';
import { PrismaClient } from '@prisma/client';
import { getRedisUrl, config } from '../config';
import { siteContentCapability } from '../services/siteContentTranslation';
import {
  BULK_ASYNC_MAX_STRINGS,
  BULK_MAX_CHARS_PER_STRING,
  BULK_MAX_TARGET_LANGS,
  BULK_REQUEST_CHAR_BUDGET,
  BULK_SYNC_MAX_STRINGS,
} from '../config/batchLimits';
import { BULK_CONTENT_MAX_ITEMS } from '../types';
import Redis from 'ioredis';

const router = Router();
const prisma = new PrismaClient();

/**
 * Basic health check
 * Returns 200 if service is running
 */
router.get('/', (_req: Request, res: Response) => {
  res.json({
    status: 'healthy',
    service: 'translate-api',
    version: '1.0.0',
    capabilities: {
      siteContentSegmentedTranslation: siteContentCapability(config.maxAsyncChars),
      bulkStringTranslation: {
        syncMaxStrings: BULK_SYNC_MAX_STRINGS,
        asyncMaxStrings: BULK_ASYNC_MAX_STRINGS,
        maxCharsPerString: BULK_MAX_CHARS_PER_STRING,
        requestCharBudget: BULK_REQUEST_CHAR_BUDGET,
        maxTargetLangs: BULK_MAX_TARGET_LANGS,
        version: 1,
      },
      bulkContentTranslation: {
        maxItems: BULK_CONTENT_MAX_ITEMS,
        maxCharsPerItem: config.maxAsyncChars,
        version: 1,
      },
    },
    timestamp: new Date().toISOString(),
  });
});

/**
 * Readiness check
 * Checks if service is ready to accept requests
 * Verifies database and Redis connections
 */
router.get('/ready', async (_req: Request, res: Response) => {
  const checks: Record<string, { status: string; error?: string }> = {};

  // Check database
  try {
    await prisma.$queryRaw`SELECT 1`;
    checks.database = { status: 'healthy' };
  } catch (error) {
    checks.database = {
      status: 'unhealthy',
      error: error instanceof Error ? error.message : 'Unknown error',
    };
  }

  // Check Redis
  let redis: Redis | undefined;
  try {
    redis = new Redis(getRedisUrl(), {
      maxRetriesPerRequest: 1,
      connectTimeout: 1000,
    });

    await redis.ping();
    checks.redis = { status: 'healthy' };
  } catch (error) {
    checks.redis = {
      status: 'unhealthy',
      error: error instanceof Error ? error.message : 'Unknown error',
    };
  } finally {
    redis?.disconnect();
  }

  // Determine overall health
  const allHealthy = Object.values(checks).every((check) => check.status === 'healthy');

  res.status(allHealthy ? 200 : 503).json({
    status: allHealthy ? 'ready' : 'not ready',
    checks,
    timestamp: new Date().toISOString(),
  });
});

/**
 * Liveness check
 * Returns 200 if service is alive (but might not be ready to serve traffic)
 */
router.get('/live', (_req: Request, res: Response) => {
  res.json({
    status: 'alive',
    uptime: process.uptime(),
    memory: process.memoryUsage(),
    timestamp: new Date().toISOString(),
  });
});

export default router;
