import { verifySession } from '@/lib/auth/dal';
import { fetchStudentMembers } from '@/lib/data/repositories/student-member-repository';
import { parseStudentMemberQuery } from '@/lib/domain/student-member-query';
import { StudentList } from './_components/student-list';

// cookies()로 이미 동적이지만, 정적 프리렌더로 데이터가 빌드 산출물에 박히는 경로를
// 원천 차단하기 위해 명시적으로 강제한다.
export const dynamic = 'force-dynamic';

interface PageProps {
  searchParams: Promise<Record<string, string | string[] | undefined>>;
}

export default async function Page({ searchParams }: PageProps) {
  await verifySession();

  const query = parseStudentMemberQuery(await searchParams);
  const { items, totalCount, isTotalCountExact } =
    await fetchStudentMembers(query);

  // 전체 건수가 확정되지 않았다면(백엔드가 count를 주지 않아 하한값만 아는 상태) 다음 페이지를
  // 한 칸 열어 둔다 — 열어 두지 않으면 가득 찬 페이지 뒤의 데이터에 접근할 방법이 없어진다.
  const totalPages = isTotalCountExact
    ? Math.max(1, Math.ceil(totalCount / query.pageSize))
    : query.page + 1;
  const currentPage = Math.min(query.page, totalPages);

  return (
    <StudentList
      items={items}
      query={query}
      currentPage={currentPage}
      totalPages={totalPages}
      totalCount={totalCount}
    />
  );
}
