import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { isAdminRequestAuthorized, resolveAdminAccount } from "@/lib/admin-auth";

export async function GET(request: NextRequest) {
  if (!isAdminRequestAuthorized(request)) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const checks = {
    db: { ok: false as boolean, error: undefined as string | undefined, task_count: 0 },
    recent_audit_events: { ok: false as boolean, error: undefined as string | undefined, count: 0 },
  };

  try {
    checks.db.task_count = await prisma.task.count();
    checks.db.ok = true;
  } catch (error) {
    checks.db.error = error instanceof Error ? error.message : "unknown";
  }

  try {
    checks.recent_audit_events.count = await prisma.auditEvent.count({
      where: {
        createdAt: {
          gte: new Date(Date.now() - 10 * 60 * 1000),
        },
      },
    });
    checks.recent_audit_events.ok = true;
  } catch (error) {
    checks.recent_audit_events.error = error instanceof Error ? error.message : "unknown";
  }

  const admin = resolveAdminAccount();

  return NextResponse.json({
    service: "agent-bounty-web",
    healthy: checks.db.ok && checks.recent_audit_events.ok,
    timestamp: new Date().toISOString(),
    admin: {
      username: admin.username,
      using_default_account: admin.isDefaultCredentials,
    },
    checks,
  });
}

