import type { Metadata } from 'next';
import Link from 'next/link';
import { Alert } from '@/components/ui/alert';
import { Pagination } from '@/components/ui/pagination';
import { verifySession } from '@/lib/auth/dal';
import { fetchBoardPosts } from '@/lib/data/repositories/board-post-repository';
import {
  buildBoardPostHref,
  parseBoardPostQuery,
} from '@/lib/domain/board-post-query';
import { BoardFilterBar } from '../_components/board-filter-bar';
import { BoardListToolbar } from '../_components/board-list-toolbar';
import { NoticeTable } from './_components/notice-table';

export const metadata: Metadata = {
  title: '공지사항',
};

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

/**
 * 공지사항 목록 — 시안 A_BOA_006.
 *
 * 전체 건수가 **확정값**이라 페이지 수를 그대로 계산한다 — Repository가 백엔드 페이징을 쓰지 않고
 * 전체를 받아 직접 세기 때문이다(백엔드 `totalCount`는 현재 페이지 행 수라 신뢰할 수 없다).
 */
export default async function Page({ searchParams }: PageProps) {
  await verifySession();

  const query = parseBoardPostQuery('notice', await searchParams);
  const { items, totalCount } = await fetchBoardPosts('notice', query);

  const totalPages = Math.max(1, Math.ceil(totalCount / query.pageSize));
  // 요청 페이지가 범위를 벗어나면(예: 삭제로 마지막 페이지가 사라짐) 마지막 페이지로 맞춘다 —
  // 표의 순번 계산도 이 값을 기준으로 해야 헤더의 "현재페이지"와 어긋나지 않는다.
  const currentPage = Math.min(query.page, totalPages);

  return (
    <section className="flex flex-1 flex-col gap-6 p-8">
      <h1 className="text-headline-sm text-foreground">공지사항 목록</h1>

      <BoardFilterBar boardType="notice" query={query} />

      <BoardListToolbar boardType="notice" query={query} canCreate />

      <p className="text-body-md text-foreground-muted">
        총 {totalCount}개 | 현재페이지 {currentPage}/{totalPages}
      </p>

      {items.length === 0 ? (
        <Alert
          title="검색 결과가 없습니다."
          actions={
            <Link
              href={buildBoardPostHref('notice', query, {
                keyword: '',
                page: 1,
              })}
              className="bg-foreground px-4 py-2 text-background"
            >
              확인
            </Link>
          }
        >
          다른 검색어로 다시 시도해 주세요.
        </Alert>
      ) : (
        <>
          <NoticeTable
            items={items}
            page={currentPage}
            pageSize={query.pageSize}
            totalCount={totalCount}
          />
          <Pagination
            currentPage={currentPage}
            totalPages={totalPages}
            buildHref={(page: number) =>
              buildBoardPostHref('notice', query, { page })
            }
          />
        </>
      )}
    </section>
  );
}
