import { NextRequest, NextResponse } from "next/server";
import { db, isDatabaseAvailable } from "@/lib/db";
import { ensureDatabaseInitialized } from "@/lib/db/init";
import { getAdminUser } from "@/lib/auth/admin";
import { clientIp } from "@/lib/auth/rateLimit";
import {
  logSecurityEventAsync,
  SecurityEventType,
} from "@/lib/auth/securityEvents";
import { count, gt } from "drizzle-orm";
import { sessions } from "@/lib/schema/db";

export const runtime = "nodejs";

export async function GET(req: NextRequest) {
  const admin = await getAdminUser();
  if (!admin) return NextResponse.json({ error: 'Forbidden' }, { status: 403 });

  logSecurityEventAsync({
    type: SecurityEventType.ADMIN_ACTION,
    userId: admin.id,
    email: admin.email,
    ip: clientIp(req),
    userAgent: req.headers.get("user-agent"),
    metadata: { route: "/api/admin/system", method: "GET" },
  });

  const dbStatus = await isDatabaseAvailable();
  let activeSessionsCount = 0;

  if (dbStatus) {
    await ensureDatabaseInitialized();
    try {
      const rows = await db
        .select({ value: count() })
        .from(sessions)
        .where(gt(sessions.expiresAt, new Date()));
      activeSessionsCount = Number(rows[0]?.value ?? 0);
    } catch (e) {
      console.error("Failed to fetch active sessions", e);
    }
  }

  const services = [
    {
      name: "PostgreSQL",
      key: "postgres",
      status: dbStatus ? "connected" : "error",
      message: dbStatus ? undefined : "Database unreachable",
    },
    {
      name: "Stripe",
      key: "stripe",
      status: process.env.STRIPE_SECRET_KEY ? "connected" : "not_configured",
    },
    {
      name: "SMTP",
      key: "smtp",
      status: process.env.SMTP_HOST && process.env.SMTP_USER ? "connected" : "not_configured",
    },
    {
      name: "Google OAuth",
      key: "google_oauth",
      status:
        process.env.GOOGLE_CLIENT_ID && process.env.GOOGLE_CLIENT_SECRET
          ? "connected"
          : "not_configured",
    },
    {
      name: "R2 Storage",
      key: "r2",
      status:
        process.env.R2_ACCESS_KEY_ID && process.env.R2_SECRET_ACCESS_KEY
          ? "connected"
          : "not_configured",
    },
    {
      name: "Discord",
      key: "discord",
      status: process.env.DISCORD_CLIENT_ID ? "connected" : "not_configured",
    },
  ];

  return NextResponse.json({
    services,
    activeSessions: activeSessionsCount,
    environment: process.env.NODE_ENV || 'development',
    appUrl: process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000',
    uptime: Math.floor(process.uptime()),
  });
}