import { isUp, type HealthStatus } from "@/lib/status";

// The "Not Working Since" rules (spec §15–16), kept pure so they can be
// tested without a database. A Slow response counts as "up": the API
// answered, so it neither starts nor prolongs an outage.

export type PreviousHealth = {
  failureStartedAt: Date | null;
  lastRecoveredAt: Date | null;
};

export type HealthTransition = {
  failureStartedAt: Date | null;
  lastRecoveredAt: Date | null;
  /** Set only on the check that starts or ends an outage. */
  event: "failure_started" | "recovered" | null;
};

export function nextHealth(previous: PreviousHealth, status: HealthStatus, checkedAt: Date): HealthTransition {
  if (!isUp(status)) {
    // The start of an outage is recorded once and never overwritten by later
    // failures — including when the very first check of an app fails.
    const alreadyFailing = previous.failureStartedAt !== null;
    return {
      failureStartedAt: previous.failureStartedAt ?? checkedAt,
      lastRecoveredAt: previous.lastRecoveredAt,
      event: alreadyFailing ? null : "failure_started",
    };
  }

  const wasFailing = previous.failureStartedAt !== null;
  return {
    failureStartedAt: null,
    lastRecoveredAt: wasFailing ? checkedAt : previous.lastRecoveredAt,
    event: wasFailing ? "recovered" : null,
  };
}
