'use server';

import { ResultDto } from '@/types/response/common';
import { StockListResponse, StockDetailResponse, StockHistoryResponse } from '@/types/stock';
import { fetchJson } from '@/lib/utils/server';

// 종목 목록 조회 (시장 필터/검색/페이징)
export async function fetchStockList(params: { q?: string; market?: string; page?: number; perPage?: number }): Promise<ResultDto<StockListResponse>>
{
	const queryParams = new URLSearchParams();

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

	if (params.q) queryParams.set('q', params.q);
	if (params.market) queryParams.set('market', params.market);

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

// 종목 상세 조회 (마스터 + 최근 시세)
export async function fetchStockDetail(code: string): Promise<ResultDto<StockDetailResponse>>
{
	return await fetchJson<StockDetailResponse>(`/api/stocks/${encodeURIComponent(code)}`, {
		method: 'GET',
		headers: {
			'Accept': 'application/json'
		}
	});
}

// 일별 시세 히스토리 조회 (페이징)
export async function fetchStockHistory(code: string, params: { page?: number; perPage?: number; from?: string; to?: string }): Promise<ResultDto<StockHistoryResponse>>
{
	const queryParams = new URLSearchParams();

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

	if (params.from) queryParams.set('from', params.from);
	if (params.to) queryParams.set('to', params.to);

	return await fetchJson<StockHistoryResponse>(`/api/stocks/${encodeURIComponent(code)}/history?${queryParams.toString()}`, {
		method: 'GET',
		headers: {
			'Accept': 'application/json'
		}
	});
}