import type { Metadata } from 'next';
import { verifySession } from '@/lib/auth/dal';
import { fetchCommonCodes } from '@/lib/data/repositories/common-code-repository';
import { fetchDecorationItems } from '@/lib/data/repositories/decoration-item-repository';
import { CODE_GROUP } from '@/lib/domain/common-code';
import { parseDecorationItemQuery } from '@/lib/domain/decoration-item-query';
import { DecorationItemList } from './_components/decoration-item-list';

export const metadata: Metadata = {
  title: '꾸미기 아이템',
};

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

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

/**
 * 꾸미기 아이템 목록(시안 ADM_ITM_101 — 5227:3549).
 *
 * **셋트아이템은 별도 화면이 없다** — 유형 탭(개별/셋트)만 바꿔 같은 목록·같은 폼을 재사용
 * 한다(시안 두 곳에 명시된 사양). `query.itemType`이 곧 그 탭 상태이고, 검색·페이지와 마찬가지로
 * URL(searchParams)이 단일 진실원천이다.
 */
export default async function Page({ searchParams }: PageProps) {
  await verifySession();

  const query = parseDecorationItemQuery(await searchParams);
  // 목록과 카테고리는 서로를 기다릴 이유가 없어 함께 띄운다.
  const [{ items, totalCount, isTotalCountExact, typeTotalCount }, categories] =
    await Promise.all([
      fetchDecorationItems(query),
      fetchCommonCodes(CODE_GROUP.decorationItemCategory),
    ]);

  // 전체 건수가 확정되지 않았다면(백엔드가 count를 주지 않아 하한값만 아는 상태) 다음 페이지를
  // 한 칸 열어 둔다 — 열어 두지 않으면 가득 찬 페이지 뒤의 데이터에 접근할 방법이 없어진다
  // (Repository 주석 참조).
  const totalPages = isTotalCountExact
    ? Math.max(1, Math.ceil(totalCount / query.pageSize))
    : query.page + 1;
  // 요청 페이지가 범위를 벗어나면(삭제로 마지막 페이지가 사라짐, 유형 탭 전환으로 건수가 줄어듦)
  // 마지막 페이지로 맞춘다 — 표의 순번도 이 값을 기준으로 세야 페이지 표시와 어긋나지 않는다.
  const currentPage = Math.min(query.page, totalPages);

  return (
    <DecorationItemList
      items={items}
      query={query}
      currentPage={currentPage}
      totalPages={totalPages}
      totalCount={totalCount}
      typeTotalCount={typeTotalCount}
      categories={categories}
    />
  );
}
