'use server';

// D3 보상/레벨/응원/지위아이템 서버 사이드 API (SSR / Server Action)
// Backend Web.Api/Endpoints/{Rewards/Today, Member/Level, Member/*, Forum/PostCheer/*}.cs 대응.
import { ResultDto } from '@/types/response/common';
import {
	MemberLevelResponse,
	RewardsTodayResponse,
	CheerListResponse,
	MemberItemsResponse,
	EquippedItemsResponse
} from '@/types/reward';
import { fetchJson } from '@/lib/utils/server';

const JSON_HEADERS = { 'Accept': 'application/json' } as const;

// 내 레벨 요약 (JWT) — GET /api/members/me/level
export async function fetchMyLevel(): Promise<ResultDto<MemberLevelResponse>>
{
	return await fetchJson<MemberLevelResponse>('/api/members/me/level', {
		method: 'GET',
		headers: JSON_HEADERS
	});
}

// 오늘 획득 보상 + 캡 잔여 (JWT) — GET /api/rewards/me/today
export async function fetchRewardsToday(): Promise<ResultDto<RewardsTodayResponse>>
{
	return await fetchJson<RewardsTodayResponse>('/api/rewards/me/today', {
		method: 'GET',
		headers: JSON_HEADERS
	});
}

// 글 응원 합계 + 최근 N건 (익명) — GET /api/posts/{postID}/cheers?take=
export async function fetchPostCheers(postID: number, take = 20): Promise<ResultDto<CheerListResponse>>
{
	return await fetchJson<CheerListResponse>(`/api/posts/${postID}/cheers?take=${take}`, {
		method: 'GET',
		headers: JSON_HEADERS
	});
}

// 내 지위 아이템 보관함 (JWT) — GET /api/members/me/items
export async function fetchMyStatusItems(params: { includeExpired?: boolean; page?: number; perPage?: number } = {}): Promise<ResultDto<MemberItemsResponse>>
{
	const queryParams = new URLSearchParams();

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

	if (params.includeExpired) {
		queryParams.set('includeExpired', 'true');
	}

	return await fetchJson<MemberItemsResponse>(`/api/members/me/items?${queryParams.toString()}`, {
		method: 'GET',
		headers: JSON_HEADERS
	});
}

// 장착 지위 아이템 배치 조회 (익명) — GET /api/members/equipped-items?ids=1,2,3
export async function fetchEquippedItems(memberIDs: number[]): Promise<ResultDto<EquippedItemsResponse>>
{
	const ids = memberIDs.filter(id => id > 0).join(',');

	return await fetchJson<EquippedItemsResponse>(`/api/members/equipped-items?ids=${ids}`, {
		method: 'GET',
		headers: JSON_HEADERS
	});
}
