import { redirect } from 'next/navigation';
import Link from 'next/link';
import { ChevronLeft } from 'lucide-react';
import { getCurrentUser } from '@/lib/auth';
import { prisma } from '@/lib/prisma';
import HistoryList from '@/components/ai/HistoryList';

export const dynamic = 'force-dynamic';

export default async function HistoryPage() {
  const user = await getCurrentUser();
  if (!user) redirect('/auth/login');

  const rows = await prisma.aIGeneration.findMany({
    where: { userId: user.id },
    orderBy: { createdAt: 'desc' },
    take: 25,
    select: {
      id: true,
      templateName: true,
      userInput: true,
      provider: true,
      model: true,
      tokensIn: true,
      tokensOut: true,
      durationMs: true,
      status: true,
      errorMessage: true,
      appliedProgramId: true,
      createdAt: true,
    },
  });

  return (
    <div className="min-h-screen bg-[#0A0A0A]">
      <div className="border-b border-zinc-800">
        <div className="max-w-3xl mx-auto px-4 py-4 sm:py-6 flex items-center gap-3">
          <Link href="/main/ai" className="text-zinc-400 hover:text-white">
            <ChevronLeft className="w-5 h-5" />
          </Link>
          <h1 className="text-2xl sm:text-3xl font-bold text-white">
            AI · Generation history
          </h1>
        </div>
      </div>
      <div className="max-w-3xl mx-auto px-4 py-6">
        <HistoryList
          initialRows={rows.map((r) => ({
            ...r,
            createdAt: r.createdAt.toISOString(),
          }))}
        />
      </div>
    </div>
  );
}
