import { Hono } from 'hono';
import { Queue } from 'bullmq';
import { prisma } from '../utils/prisma';
import Redis from 'ioredis';
import { appConfig } from '../config';
import { getWorkerConfig } from '@wcag-ada/config';

const healthRoutes = new Hono();

healthRoutes.get('/', async (c) => {
  const checks = {
    api: 'ok',
    database: 'unknown',
    redis: 'unknown',
    queue: 'unknown',
  };
  
  // Check database
  try {
    await prisma.$queryRaw`SELECT 1`;
    checks.database = 'ok';
  } catch (error) {
    checks.database = 'error';
  }
  
  // Check Redis
  try {
    const workerConfig = getWorkerConfig();
    const redis = new Redis({
      host: workerConfig.redis.host,
      port: workerConfig.redis.port,
      password: workerConfig.redis.password,
      db: workerConfig.redis.db,
    });
    await redis.ping();
    await redis.quit();
    checks.redis = 'ok';
  } catch (error) {
    checks.redis = 'error';
  }
  
  // Check queue
  try {
    const workerConfig = getWorkerConfig();
    const queue = new Queue(workerConfig.queueName, {
      connection: new Redis({
        host: workerConfig.redis.host,
        port: workerConfig.redis.port,
        password: workerConfig.redis.password,
        db: workerConfig.redis.db,
      }),
    });
    await queue.getJobCounts();
    await queue.close();
    checks.queue = 'ok';
  } catch (error) {
    checks.queue = 'error';
  }
  
  const allHealthy = Object.values(checks).every(status => status === 'ok');
  
  return c.json(
    {
      status: allHealthy ? 'healthy' : 'unhealthy',
      checks,
      timestamp: new Date().toISOString(),
    },
    allHealthy ? 200 : 503
  );
});

healthRoutes.get('/stats', async (c) => {
  try {
    // Get queue stats
    const workerConfig = getWorkerConfig();
    const queue = new Queue(workerConfig.queueName, {
      connection: new Redis({
        host: workerConfig.redis.host,
        port: workerConfig.redis.port,
        password: workerConfig.redis.password,
        db: workerConfig.redis.db,
      }),
    });
    
    const [waiting, active, completed, failed] = await Promise.all([
      queue.getWaitingCount(),
      queue.getActiveCount(),
      queue.getCompletedCount(),
      queue.getFailedCount(),
    ]);
    
    const queueStats = { waiting, active, completed, failed };
    
    const dbStats = await Promise.all([
      prisma.user.count(),
      prisma.website.count({ where: { active: true } }),
      prisma.scanJob.count(),
      prisma.scanResult.count(),
    ]);
    
    await queue.close();
    
    return c.json({
      queue: queueStats,
      database: {
        users: dbStats[0],
        websites: dbStats[1],
        scanJobs: dbStats[2],
        scanResults: dbStats[3],
      },
      timestamp: new Date().toISOString(),
    });
  } catch (error) {
    return c.json({ error: 'Failed to get stats' }, 500);
  }
});

export { healthRoutes };