import { NextResponse } from "next/server";
import * as fs from "node:fs";
import * as path from "node:path";
import { prisma } from "@/lib/prisma";

export const dynamic = "force-dynamic";
export const revalidate = 0;

/**
 * GET /api/health
 *
 * Health check endpoint. Reports:
 *   - status: 'ok' if every check passed, 'error' otherwise
 *   - database.connected: was the count query successful?
 *   - database.journalMode: 'wal' is the only acceptable value in
 *     production (entrypoint sets it on every boot)
 *   - users / instanceSettings.signupsOpen: cheap surface metadata
 *   - library.available: did exercises.seed.json load? Should be true
 *     in any properly-built image.
 *
 * Used by StartOS health checks (port-listening AND content checks)
 * plus Docker HEALTHCHECK. Excluded from auth middleware.
 */
export async function GET() {
  const checks: Record<string, unknown> = {};
  let httpStatus = 200;

  // ---- Database --------------------------------------------------------
  try {
    const userCount = await prisma.user.count();
    const settings = await prisma.instanceSettings.findUnique({
      where: { id: 1 },
    });
    const journalRows = await prisma.$queryRawUnsafe<Array<{ journal_mode: string }>>(
      'PRAGMA journal_mode;',
    );
    const journalMode = journalRows[0]?.journal_mode ?? 'unknown';

    checks.database = {
      connected: true,
      journalMode,
      walEnabled: journalMode === 'wal',
    };
    checks.users = userCount;
    checks.instanceSettings = {
      signupsOpen: settings?.signupsOpen ?? false,
    };
    if (journalMode !== 'wal') {
      // WAL is required for safe online backups. Surface as a warning
      // but don't fail the health check (the app still works).
      checks.warnings = [
        ...((checks.warnings as string[]) ?? []),
        `journal_mode is '${journalMode}', expected 'wal'`,
      ];
    }
  } catch (error) {
    checks.database = {
      connected: false,
      error: error instanceof Error ? error.message : 'Unknown DB error',
    };
    httpStatus = 503;
  }

  // ---- Curated library file ------------------------------------------
  try {
    const candidates = [
      path.resolve(process.cwd(), 'prisma/exercises.seed.json'),
      path.resolve(process.cwd(), '../prisma/exercises.seed.json'),
    ];
    const found = candidates.find((p) => fs.existsSync(p));
    if (found) {
      const stat = fs.statSync(found);
      checks.library = { available: true, sizeBytes: stat.size };
    } else {
      checks.library = { available: false };
    }
  } catch (error) {
    checks.library = {
      available: false,
      error: error instanceof Error ? error.message : 'unknown',
    };
  }

  return NextResponse.json(
    {
      status: httpStatus === 200 ? 'ok' : 'error',
      timestamp: Date.now(),
      ...checks,
    },
    { status: httpStatus },
  );
}
