import BoardMeta from '@/types/forum/boardMeta';
import BoardManager from '@/types/forum/boardManager';
import { MemberResponse } from '@/types/response/account/member';
import { BoardLayout } from '@/constants/forum';

// 최고관리자 또는 게시판 관리자 여부 확인
export function isBoardAdmin(
	boardManagers: BoardManager[],
	member: MemberResponse|null
): boolean {
	if (!member) {
		return false;
	}

	if (member.isAdmin) {
		return true;
	}

	return boardManagers ? boardManagers.some(m => m.user.email === member.email) : false;
}

type PermissionResult = {
	canAccessBoard: boolean;
	canViewPost: boolean;
	canWritePost: boolean;
	canViewComment: boolean;
	canWriteComment: boolean;
	canWriteReply: boolean;
	canUploadFile: boolean;
	canDownloadFile: boolean;
};

export function checkPermission(
	boardMeta: BoardMeta,
	boardManagers: BoardManager[],
	member: MemberResponse|null
): PermissionResult {
	const isQnABoard = boardMeta.list.layout === BoardLayout.QnA;

	const check = (permission: number, qnaRestricted = false): boolean =>
	{
		// 비회원은 항상 허용
		if (permission <= -1) {
			return true;
		}

		// 비로그인은 거부
		if (!member) {
			return false;
		}

		// 최고관리자는 항상 허용
		if (member.isAdmin) {
			return true;
		}

		// 게시판 관리자 여부
		const isBoardManager = boardManagers?.some(m => m.user.email === member.email) ?? false;

		// 1:1 게시판: 최고관리자/게시판 관리자만 허용 (일반 회원 거부)
		if (qnaRestricted && isQnABoard) {
			return isBoardManager;
		}

		// 유효 권한 레벨 계산 (매니저=99, 일반=memberGrade.order)
		const level = isBoardManager ? 99 : (member.memberGrade?.order ?? 0);

		return permission <= level;
	};

	return {
		canAccessBoard: check(boardMeta.permission.boardAccess),
		canViewPost: check(boardMeta.permission.postView),
		canWritePost: check(boardMeta.permission.postWrite),
		canViewComment: check(boardMeta.permission.commentView),
		canWriteComment: check(boardMeta.permission.commentWrite, true),
		canWriteReply: check(boardMeta.permission.replyWrite, true),
		canUploadFile: check(boardMeta.permission.fileUpload),
		canDownloadFile: check(boardMeta.permission.fileDownload)
	};
}