import { getDb } from "@/lib/db";
import fs from "fs/promises";
import { withErrorHandling, json } from "@/lib/api/errors";

/**
 * Next.js Route Handler caching configuration (RHL-006):
 *
 * We force this route to execute dynamically on every request.
 *
 * Reasons:
 * - NAS contents can change at any time (new scans).
 * - Auth/RBAC-protected responses must not be cached/shared across users.
 * - We rely on a small storage-layer TTL micro-cache instead of Next route caching.
 */
export const dynamic = "force-dynamic";

/**
 * GET /api/health
 *
 * Health check endpoint:
 * - Verifies database connectivity.
 * - Verifies readability of NAS_ROOT_PATH.
 *
 * Note:
 * - This endpoint returns 200 even if sub-checks fail,
 *   because it is used to surface partial system state.
 * - Unexpected failures (coding bugs, etc.) are still handled by withErrorHandling().
 */
export const GET = withErrorHandling(
	async function GET() {
		const result = {
			db: null,
			nas: null,
		};

		// --- Database health ---------------------------------------------------
		try {
			const db = await getDb();
			await db.command({ ping: 1 });
			result.db = "ok";
		} catch (error) {
			// We don't throw here – we report the error in the JSON result
			result.db = `error: ${error.message}`;
		}

		// --- NAS health --------------------------------------------------------
		const nasPath = process.env.NAS_ROOT_PATH || "/mnt/niederlassungen";

		try {
			const entries = await fs.readdir(nasPath);
			result.nas = {
				path: nasPath,
				entriesSample: entries.slice(0, 5),
			};
		} catch (error) {
			// It's okay if NAS is not available in some environments (like local dev),
			// we just propagate the error message in the health object.
			result.nas = `error: ${error.message}`;
		}

		return json(result, 200);
	},
	{ logPrefix: "[api/health]" }
);
