import Elysia, { t } from "elysia";

import { env } from "@/env";
import { redis } from "@/services/redis";
import { baseLogger } from "@/utils/logger";

const healthLogger = baseLogger.child({
    module: "health",
});

export const healthRoutes = new Elysia().get(
    "/health",
    async ({ status }) => {
        const perf = performance.now();
        let healthy = true;
        try {
            await redis.ping();
        } catch (e) {
            healthLogger.error("Redis connection error:", e);

            healthy = false;
        }

        const duration = performance.now() - perf;
        const durationString = `${duration.toFixed(2)} ms`;

        if (!healthy) {
            healthLogger.error("Health check failed");
            return status(503, {
                healthy,
                version: env.VERSION,
                duration: durationString,
            });
        }

        return {
            healthy,
            version: env.VERSION,
            duration: durationString,
        };
    },
    {
        response: {
            200: t.Object({
                healthy: t.Boolean(),
                version: t.String(),
                duration: t.String(),
            }),
            503: t.Object({
                healthy: t.Boolean(),
                version: t.String(),
                duration: t.String(),
            }),
        },
    },
);
