import "server-only";

import type { HealthStatus } from "@/lib/status";
import { db } from "../db";

export const HISTORY_PAGE_SIZE = 25;

/** Newest first, one page at a time — history is never loaded unbounded. */
export async function listHealthChecks(projectId: string, page: number, status: HealthStatus | null = null) {
  const where = { projectId, ...(status ? { status } : {}) };

  const [total, checks] = await Promise.all([
    db.healthCheck.count({ where }),
    db.healthCheck.findMany({
      where,
      orderBy: [{ checkedAt: "desc" }, { id: "desc" }],
      skip: (page - 1) * HISTORY_PAGE_SIZE,
      take: HISTORY_PAGE_SIZE,
    }),
  ]);

  return { checks, total, pageCount: Math.max(1, Math.ceil(total / HISTORY_PAGE_SIZE)) };
}

export type HealthStats = {
  days: number;
  total: number;
  working: number;
  slow: number;
  notWorking: number;
  /** Share of checks that got a response (Working or Slow); null before the first check. */
  uptimePercent: number | null;
  averageResponseMs: number | null;
  slowestResponseMs: number | null;
};

/** Outcome counts and response-time figures over the last `days` days. */
export async function getHealthStats(projectId: string, days = 30): Promise<HealthStats> {
  const since = new Date(Date.now() - days * 86_400_000);
  const [row] = await db.$queryRaw<
    Array<{ total: number; working: number; slow: number; notWorking: number; average: number | null; slowest: number | null }>
  >`
    SELECT
      COUNT(*)::int                                                         AS total,
      COUNT(*) FILTER (WHERE status = 'WORKING')::int                       AS working,
      COUNT(*) FILTER (WHERE status = 'SLOW')::int                          AS slow,
      COUNT(*) FILTER (WHERE status = 'NOT_WORKING')::int                   AS "notWorking",
      ROUND(AVG(response_time_ms) FILTER (WHERE status <> 'NOT_WORKING'))::int AS average,
      MAX(response_time_ms) FILTER (WHERE status <> 'NOT_WORKING')::int     AS slowest
    FROM health_checks
    WHERE project_id = ${projectId} AND checked_at >= ${since}`;

  return {
    days,
    total: row.total,
    working: row.working,
    slow: row.slow,
    notWorking: row.notWorking,
    uptimePercent: row.total === 0 ? null : ((row.working + row.slow) / row.total) * 100,
    averageResponseMs: row.average,
    slowestResponseMs: row.slowest,
  };
}

export type RecentOutcome = { id: string; checkedAt: Date; status: HealthStatus; responseTimeMs: number | null };

/** The latest `limit` outcomes, oldest first — feeds the status timeline strip. */
export async function listRecentOutcomes(projectId: string, limit = 60): Promise<RecentOutcome[]> {
  const rows = await db.healthCheck.findMany({
    where: { projectId },
    orderBy: [{ checkedAt: "desc" }, { id: "desc" }],
    take: limit,
    select: { id: true, checkedAt: true, status: true, responseTimeMs: true },
  });
  return rows.reverse();
}
