/**
 * WorthDoing.ai
 * Author: Simon-Pierre Boucher
 * Contact: contact@spboucher.ai
 * File: src/app/history/page.tsx
 * Description: History page — all investigations with status, phase, outcome and telemetry.
 */
import Link from "next/link";
import { desc } from "drizzle-orm";
import { db } from "@/lib/db/client";
import { investigations } from "@/lib/db/schema";
import { InvestigationStatusBadge, PhaseBadge } from "@/components/wd/badges";

export const dynamic = "force-dynamic";

export default async function HistoryPage() {
  const rows = await db.select().from(investigations).orderBy(desc(investigations.createdAt)).limit(100);

  return (
    <div className="mx-auto w-full max-w-4xl px-4 py-10 sm:px-6">
      <h1 className="font-heading text-3xl font-semibold tracking-tight text-ink sm:text-4xl">
        Investigation history
      </h1>

      {rows.length === 0 ? (
        <div className="mt-16 rounded-xl border border-dashed border-line bg-card/50 p-12 text-center">
          <p className="font-heading text-xl text-ink">No investigations yet</p>
          <p className="mt-2 text-sm text-ink-soft">Launch one from the home page.</p>
        </div>
      ) : (
        <ul className="mt-8 space-y-3">
          {rows.map((inv) => (
            <li key={inv.id}>
              <Link
                href={`/investigate/${inv.id}`}
                className="block rounded-xl border border-line bg-card p-4 transition-colors hover:border-verdict/40"
              >
                <div className="flex flex-wrap items-center gap-2">
                  <InvestigationStatusBadge status={inv.status} live />
                  <PhaseBadge phase={inv.phase} />
                  <span className="ml-auto font-mono text-[11px] text-ink-soft">
                    {inv.createdAt.toLocaleString([], {
                      year: "numeric",
                      month: "short",
                      day: "numeric",
                      hour: "2-digit",
                      minute: "2-digit",
                    })}
                  </span>
                </div>
                <p className="mt-2 text-[15px] font-medium leading-snug text-ink">{inv.objective}</p>
                {inv.conclusion && (
                  <p className="mt-1 line-clamp-2 text-sm text-ink-soft">{inv.conclusion}</p>
                )}
                <p className="mt-2 font-mono text-[10px] uppercase tracking-wider text-ink-soft/80">
                  {inv.budgetUsed.searches} searches · {inv.budgetUsed.scrapes} reads ·{" "}
                  {inv.budgetUsed.agentSteps} steps · ${inv.budgetUsed.costUsd.toFixed(2)}
                </p>
              </Link>
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}
