/**
 * GET /api/eterra/stats
 *
 * Lightweight endpoint for the monitor page — returns aggregate counts
 * suitable for polling every 30s without heavy DB load.
 *
 * Response:
 * {
 *   totalUats: number,
 *   totalFeatures: number,
 *   totalTerenuri: number,
 *   totalCladiri: number,
 *   totalEnriched: number,
 *   totalNoGeom: number,
 *   countiesWithData: number,
 *   lastSyncAt: string | null,
 *   dbSizeMb: number | null,
 * }
 */

import { prisma } from "@/core/storage/prisma";
import { NextResponse } from "next/server";

export const runtime = "nodejs";
export const dynamic = "force-dynamic";

export async function GET() {
  try {
    const [
      totalUats,
      totalFeatures,
      totalTerenuri,
      totalCladiri,
      totalEnriched,
      totalNoGeom,
      countyAgg,
      lastSync,
      dbSize,
    ] = await Promise.all([
      prisma.gisUat.count(),
      prisma.gisFeature.count({ where: { objectId: { gt: 0 } } }),
      prisma.gisFeature.count({ where: { layerId: "TERENURI_ACTIVE", objectId: { gt: 0 } } }),
      prisma.gisFeature.count({ where: { layerId: "CLADIRI_ACTIVE", objectId: { gt: 0 } } }),
      prisma.gisFeature.count({ where: { enrichedAt: { not: null } } }),
      prisma.gisFeature.count({ where: { geometrySource: "NO_GEOMETRY" } }),
      prisma.gisUat.groupBy({
        by: ["county"],
        where: { county: { not: null } },
        _count: true,
      }),
      prisma.gisSyncRun.findFirst({
        where: { status: "done" },
        orderBy: { completedAt: "desc" },
        select: { completedAt: true },
      }),
      prisma.$queryRaw<Array<{ size: string }>>`
        SELECT pg_size_pretty(pg_database_size(current_database())) as size
      `,
    ]);

    // Parse DB size to MB
    const sizeStr = dbSize[0]?.size ?? "";
    let dbSizeMb: number | null = null;
    const mbMatch = sizeStr.match(/([\d.]+)\s*(MB|GB|TB)/i);
    if (mbMatch) {
      const val = parseFloat(mbMatch[1]!);
      const unit = mbMatch[2]!.toUpperCase();
      dbSizeMb = unit === "GB" ? val * 1024 : unit === "TB" ? val * 1024 * 1024 : val;
    }

    return NextResponse.json({
      totalUats,
      totalFeatures,
      totalTerenuri,
      totalCladiri,
      totalEnriched,
      totalNoGeom,
      countiesWithData: countyAgg.length,
      lastSyncAt: lastSync?.completedAt?.toISOString() ?? null,
      dbSizeMb: dbSizeMb ? Math.round(dbSizeMb) : null,
    });
  } catch (error) {
    const message = error instanceof Error ? error.message : "Eroare server";
    return NextResponse.json({ error: message }, { status: 500 });
  }
}
