import { desc } from "drizzle-orm";

import { jsonSuccess } from "@/modules/core/server/api";
import { requirePermission } from "@/modules/core/server/auth";
import { checkDatabaseConnection, getDatabase } from "@/modules/core/server/db";
import { accounts, beds, elders, organizations, systemIncidents } from "@/modules/core/server/schema";

export async function GET(): Promise<Response> {
  const auth = await requirePermission("incident:read", {
    action: "system.status",
    targetType: "systemStatus",
  });

  if (!auth.success) {
    return auth.response;
  }

  const health = await checkDatabaseConnection();
  const database = getDatabase();
  const [organizationRows, accountRows, elderRows, bedRows, incidentRows] = await Promise.all([
    database.select({ id: organizations.id }).from(organizations),
    database.select({ id: accounts.id }).from(accounts),
    database.select({ id: elders.id }).from(elders),
    database.select({ id: beds.id }).from(beds),
    database.select().from(systemIncidents).orderBy(desc(systemIncidents.createdAt)).limit(20),
  ]);

  return jsonSuccess("系统运行状态已加载", {
    health,
    metrics: {
      organizations: organizationRows.length,
      accounts: accountRows.length,
      elders: elderRows.length,
      beds: bedRows.length,
      incidents: incidentRows.length,
    },
    incidents: incidentRows.map((incident) => ({
      id: incident.id,
      organizationId: incident.organizationId,
      severity: incident.severity,
      status: incident.status,
      title: incident.title,
      description: incident.description,
      source: incident.source,
      createdAt: incident.createdAt.toISOString(),
      updatedAt: incident.updatedAt.toISOString(),
    })),
  });
}
