'use server';

import './style.scss';
import View from './view';
import { BoardSort, PostSearchType } from '@/constants/forum';
import { fetchAllPosts } from '@/lib/api/forum/board';
import { throwError } from '@/lib/utils/server';

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

export default async function Latest({ searchParams }: Props)
{
	const query = await searchParams;

	query.page = Math.max(Number(query.page) || 1) as number;
	query.perPage = Math.max(Number(query.perPage) || 20) as number;
	query.sort = (Number(query.sort) || BoardSort.CreatedAt) as BoardSort|undefined;
	query.search = (Number(query.search) || PostSearchType.Subject) as PostSearchType;
	query.keyword = (query.keyword || '') as string|undefined;

	const posts = await fetchAllPosts({
		page: query.page as number,
		perPage: query.perPage as number,
		sort: query.sort as BoardSort|null|undefined,
		search: query.search as PostSearchType,
		keyword: query.keyword as string|null|undefined
	});

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

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