'use server';

import {
    BoardPostsRequest,
    AllPostsRequest
} from '@/types/request/forum/board';

import {
    BoardResponse,
    BoardListResponse,
    BoardPostsResponse
} from '@/types/response/forum/board';

import { ResultDto } from '@/types/response/common';
import { fetchJson } from '@/lib/utils/server';

// 게시판 상세 조회
export async function fetchBoard(boardCode: string): Promise<ResultDto<BoardResponse>>
{
    return await fetchJson<BoardResponse>(`/api/forum/boards/${boardCode}`, {
        method: 'GET',
        headers: {
            'Accept': 'application/json'
        }
    });
}

// 게시판 목록 조회
export async function fetchBoardList(boardGroupCode?: string): Promise<ResultDto<BoardListResponse>>
{
    const params = boardGroupCode ? `?boardGroupCode=${boardGroupCode}` : '';

    return await fetchJson<BoardListResponse>(`/api/forum/boards${params}`, {
        method: 'GET',
        headers: {
            'Accept': 'application/json'
        }
    });
}

// 전체 게시글 조회
export async function fetchAllPosts(params: AllPostsRequest): Promise<ResultDto<BoardPostsResponse>>
{
    const queryParams = new URLSearchParams();

    queryParams.set('page', String(params.page));
    queryParams.set('perPage', String(params.perPage));

    if (params.sort !== undefined && params.sort !== null) queryParams.set('sort', String(params.sort));
    if (params.search !== undefined && params.search !== null) queryParams.set('search', String(params.search));
    if (params.keyword) queryParams.set('keyword', params.keyword);

    return await fetchJson<BoardPostsResponse>(`/api/forum/posts?${queryParams.toString()}`, {
        method: 'GET',
        headers: {
            'Accept': 'application/json'
        }
    });
}

// 게시판 게시글 조회
export async function fetchBoardPosts(params: BoardPostsRequest): Promise<ResultDto<BoardPostsResponse>>
{
    const queryParams = new URLSearchParams();

    queryParams.set('boardID', String(params.boardID));
    queryParams.set('page', String(params.page));
    queryParams.set('perPage', String(params.perPage));
    queryParams.set('IsDeleted', "true");

    if (params.boardPrefixID) queryParams.set('boardPrefixID', String(params.boardPrefixID));
    if (params.sort !== undefined && params.sort !== null) queryParams.set('sort', String(params.sort));
    if (params.search !== undefined && params.search !== null) queryParams.set('search', String(params.search));
    if (params.keyword) queryParams.set('keyword', params.keyword);

    return await fetchJson<BoardPostsResponse>(`/api/forum/posts?${queryParams.toString()}`, {
        method: 'GET',
        headers: {
            'Accept': 'application/json'
        }
    });
}