import { prisma } from '@/src/lib/prisma'
import AdminClient from './AdminClient'

type AdminRecordItem = {
  id: string
  timestamp: string
  sampleCount: number
  duration: number
}

export default async function AdminPage({
  searchParams,
}: {
  searchParams: Promise<{ page?: string; pageSize?: string }>
}) {
  const params = await searchParams
  const page = Math.max(1, parseInt(params.page || '1', 10) || 1)
  const pageSizeRaw = parseInt(params.pageSize || '50', 10) || 50
  const pageSize = Math.min(100, Math.max(1, pageSizeRaw))

  const [total, rows] = await Promise.all([
    prisma.recording.count(),
    prisma.recording.findMany({
      orderBy: { timestamp: 'desc' },
      skip: (page - 1) * pageSize,
      take: pageSize,
      select: {
        id: true,
        timestamp: true,
        sample_count: true,
        duration: true,
      },
    }),
  ])

  const data: AdminRecordItem[] = rows.map((r) => ({
    id: r.id,
    timestamp: r.timestamp.toISOString(),
    sampleCount: r.sample_count,
    duration: r.duration,
  }))

  const totalPages = Math.max(1, Math.ceil(total / pageSize))

  return <AdminClient initialData={data} currentPage={page} pageSize={pageSize} totalPages={totalPages} />
}
