import { Router } from 'express';

import { db } from '../db/client';
import { mediaConfig } from '../media/config';
import { mediaProvider } from '../media/service';
import { sfuService } from '../media/sfu/service';
import { getAllMetrics } from '../observability/metrics';
import { minioBucket, minioClient } from '../utils/minio';

const router = Router();

router.get('/live', (_req, res) => {
  res.json({ status: 'ok', service: 'backend', timestamp: new Date().toISOString() });
});

router.get('/ready', async (_req, res) => {
  try {
    await db.execute('select 1');
    await minioClient.bucketExists(minioBucket);
    const sfuSessions = sfuService ? await sfuService.listSessions() : [];

    res.json({
      status: 'ready',
      checks: {
        database: 'ok',
        minio: 'ok',
        mediaMode: mediaConfig.mode,
        mediaProvider: mediaProvider.name,
        sfuService: sfuService ? sfuService.mode : 'disabled',
        sfuActiveSessions: sfuSessions.filter((session) => session.state !== 'ended').length,
      },
      timestamp: new Date().toISOString(),
    });
  } catch (error) {
    res.status(503).json({
      status: 'not_ready',
      error: error instanceof Error ? error.message : 'unknown error',
      timestamp: new Date().toISOString(),
    });
  }
});

router.get('/metrics', (_req, res) => {
  res.json({
    timestamp: new Date().toISOString(),
    metrics: getAllMetrics(),
  });
});

export default router;
