import type { VulnSummary } from "@/lib/api";
import { ageHours, relativeTime } from "./SeverityVisuals";

/*
 * Database freshness sits with the findings, not in settings.
 *
 * A fleet scanned against a three-week-old database must say so where its
 * findings are read. Quietly reporting "0 open" against stale data is the same
 * class of lie as reporting zero findings for a distribution we hold no feed
 * for — it looks exactly like good news.
 */

// Past this the banner stops being informational and starts being a warning.
// trivy-db rebuilds every six hours, so a day without a successful pull already
// means something is wrong.
const STALE_AFTER_HOURS = 24;

export function DBFreshness({ summary }: { summary?: VulnSummary }) {
    if (!summary) return null;

    const age = ageHours(summary.pulled_at);
    const stale = age === null || age > STALE_AFTER_HOURS;

    if (!stale && !summary.last_error) {
        return (
            <p className="font-mono text-[10px] uppercase tracking-[0.16em] text-text-tertiary">
                Vulnerability database v{summary.db_version ?? "?"} · pulled {relativeTime(summary.pulled_at)}
                {summary.last_full_scan_at && <> · last scan {relativeTime(summary.last_full_scan_at)}</>}
            </p>
        );
    }

    return (
        <div className="rounded-lg border border-warning/50 bg-warning/10 px-4 py-3">
            <p className="text-sm font-medium text-warning">
                {age === null ? "No vulnerability database has been pulled yet" : `Vulnerability database is ${relativeTime(summary.pulled_at)}`}
            </p>
            <p className="mt-1 text-xs text-text-secondary">
                Findings below are matched against that data. Counts may be incomplete until a fresh pull succeeds.
            </p>
            {summary.last_error && <p className="mt-2 break-words font-mono text-xs text-text-tertiary">{summary.last_error}</p>}
        </div>
    );
}
