'use server';

import './style.scss';
import View from './view';
import { notFound, forbidden, redirect } from 'next/navigation';
import { BoardLayout, BoardSort, PostSearchType } from '@/constants/forum';
import { BoardPostsRequest } from '@/types/request/forum/board';
import { checkAuthServer } from '@/lib/api/auth';
import { fetchBoard, fetchBoardPosts } from '@/lib/api/forum/board';
import { throwError, checkPermission } from '@/lib/utils/server';
import PermissionDenied from '../_component/PermissionDenied';

type Props = {
	params: Promise<{
		code: string;
	}>;
	searchParams: Promise<{
		page: number;
		perPage: number;
		prefix?: number;
		sort?: BoardSort;
		search: PostSearchType;
		keyword?: string;
	}>;
}

export default async function Board({ params, searchParams }: Props)
{
	const { code } = await params;

	if (!code) {
		return notFound();
	}

	const query = await searchParams;

	// 게시판 조회
	const board = await fetchBoard(code);

	if (!board || !board.data) {
		return notFound();
	}

	if (!board.data.isActive) {
		return forbidden();
	}

	if (!board.data.boardMeta) {
		throw new Error('게시판 속성을 찾을 수 없습니다.');
	}

	// 1:1 게시판은 로그인한 사용자만 접근 가능
	if (board.data.boardMeta.list.layout === BoardLayout.QnA && !await checkAuthServer()) {
		redirect('/login');
	}

	// 게시판 접근 권한 확인
	if (!await checkPermission(board.data.boardMeta.permission.boardAccess, board.data.boardManager)) {
		return <PermissionDenied _board={board.data} />;
	}

	query.page = Math.max(Number(query.page) || 1) as number;
	query.perPage = Math.max(Number(query.perPage) || (board.data.boardMeta.list.perPage || 10)) as number;
	query.prefix = (Number(query.prefix) || null) as number|undefined;
	query.sort = (Number(query.sort) || board.data.boardMeta.list.sort) as BoardSort|undefined;
	query.search = (Number(query.search) || PostSearchType.Subject) as PostSearchType;
	query.keyword = (query.keyword || '') as string|undefined;

	// 게시글 조회
	const boardPosts = await fetchBoardPosts({
		boardID: board.data.id as number,
		boardCode: board.data.code as string,
		page: query.page as number,
		perPage: query.perPage as number,
		boardPrefixID: query.prefix as number|null|undefined,
		sort: query.sort as BoardSort|null|undefined,
		search: query.search as PostSearchType,
		keyword: query.keyword as string|null|undefined
	} as BoardPostsRequest);

	if (!boardPosts.success) {
		throwError(boardPosts);
	}

	return (
		<View _query={query} _board={board.data} _postList={boardPosts.data!} />
	);
}