'use server';

import View from './view';
import { notFound, forbidden, unauthorized } from 'next/navigation';
import { checkAuthServer } from '@/lib/api/auth';
import { fetchBoard, fetchBoardList } from '@/lib/api/forum/board';
import { checkPermission } from '@/lib/utils/server';
import PermissionDenied from '@/app/(main)/(forum)/board/_component/PermissionDenied';

export default async function PostWrite({ searchParams }: { searchParams : Promise<{ board: string }> })
{
	const { board: boardCode } = await searchParams;

	if (!boardCode) {
		return forbidden();
	}

	try {

		if (!await checkAuthServer()) {
			throw Error;
		}

	} catch {
		return unauthorized();
	}

	try {

		// 게시판 상세 조회
		const board = await fetchBoard(boardCode);
		if (!board.success || !board.data) {
			throw Error;
		}

		// 게시글 작성 권한 확인 (본인 글이면 스킵)
		if (!await checkPermission(board.data.boardMeta.permission.postWrite, board.data.boardManager)) {
			return <PermissionDenied _board={board.data} />;
		}

		// 게시판 목록 조회
		const boardList = await fetchBoardList(board.data.boardGroup.code);

		if (!boardList.success || !boardList.data) {
			throw Error;
		}

		return (
			<View _boardList={boardList.data} _board={board.data} />
		);
	} catch {
		return notFound();
	}
}