// src/health-check.ts
import type Strapi from '@strapi/strapi';
import { Context, Next } from 'koa';

/**
 * Creates a simple health check route using TypeScript
 */
export default (strapi: any): void => {
  // Directly add a route to the Koa app
  strapi.server.app.use(async (ctx: Context, next: Next) => {
    if (ctx.path === '/_health') {
      try {
        // Run a simple database query
        await strapi.db.connection.raw('SELECT 1');
        
        // Set status and response
        ctx.status = 200;
        ctx.body = {
          status: 'ok',
          timestamp: new Date().toISOString()
        };
      } catch (error) {
        // Set error status and response
        ctx.status = 503;
        ctx.body = {
          status: 'error',
          message: 'Database connection failed',
          timestamp: new Date().toISOString()
        };
      }
      return;
    }
    
    await next();
  });
};