'use server';

import { ResultDto } from '@/types/response/common';
import {
	MarketIndicesResponse,
	EtpResponse,
	EtpTypeName,
	BondsResponse,
	BondMarketName,
	FuturesResponse,
	FuturesKindName,
	OptionsResponse,
	OptionsKindName,
	MarketSessionValue,
	CommoditiesResponse,
	CommodityMarketName,
	EsgSecuritiesResponse,
	EsgIndicesResponse,
	SriBondsResponse,
	ExchangeRatesResponse,
	InterestRatesResponse,
	RateTypeName,
	DisclosuresResponse
} from '@/types/market';
import { fetchJson } from '@/lib/utils/server';

// 공통 헤더 (익명 · JSON)
const JSON_HEADERS = { 'Accept': 'application/json' } as const;

// 지수 요약 (KOSPI/KOSDAQ/KRX/채권/파생) — 최신 1건
export async function fetchMarketIndices(): Promise<ResultDto<MarketIndicesResponse>>
{
	return await fetchJson<MarketIndicesResponse>('/api/market/indices', {
		method: 'GET',
		headers: JSON_HEADERS
	});
}

// ETP (ETF/ETN/ELW) — type 은 enum 멤버명 문자열로 전송 (ASP.NET model binding)
export async function fetchMarketEtp(params: { type?: EtpTypeName; page?: number }): Promise<ResultDto<EtpResponse>>
{
	const queryParams = new URLSearchParams();

	if (params.type) queryParams.set('type', params.type);
	queryParams.set('page', String(params.page ?? 1));

	return await fetchJson<EtpResponse>(`/api/market/etp?${queryParams.toString()}`, {
		method: 'GET',
		headers: JSON_HEADERS
	});
}

// 채권 (국채전문/일반/소액)
export async function fetchMarketBonds(params: { market?: BondMarketName; date?: string; page?: number }): Promise<ResultDto<BondsResponse>>
{
	const queryParams = new URLSearchParams();

	if (params.market) queryParams.set('market', params.market);
	if (params.date) queryParams.set('date', params.date);
	queryParams.set('page', String(params.page ?? 1));

	return await fetchJson<BondsResponse>(`/api/market/bonds?${queryParams.toString()}`, {
		method: 'GET',
		headers: JSON_HEADERS
	});
}

// 선물 (일반/주식선물) — session 은 숫자 1(정규)/2(야간) 전송, 미지정 시 백엔드 기본 정규
export async function fetchMarketFutures(params: { kind?: FuturesKindName; date?: string; page?: number; session?: MarketSessionValue }): Promise<ResultDto<FuturesResponse>>
{
	const queryParams = new URLSearchParams();

	if (params.kind) queryParams.set('kind', params.kind);
	if (params.date) queryParams.set('date', params.date);
	if (params.session) queryParams.set('session', String(params.session));
	queryParams.set('page', String(params.page ?? 1));

	return await fetchJson<FuturesResponse>(`/api/market/futures?${queryParams.toString()}`, {
		method: 'GET',
		headers: JSON_HEADERS
	});
}

// 옵션 (일반/주식옵션) — session 은 숫자 1(정규)/2(야간) 전송, 미지정 시 백엔드 기본 정규
export async function fetchMarketOptions(params: { kind?: OptionsKindName; date?: string; page?: number; session?: MarketSessionValue }): Promise<ResultDto<OptionsResponse>>
{
	const queryParams = new URLSearchParams();

	if (params.kind) queryParams.set('kind', params.kind);
	if (params.date) queryParams.set('date', params.date);
	if (params.session) queryParams.set('session', String(params.session));
	queryParams.set('page', String(params.page ?? 1));

	return await fetchJson<OptionsResponse>(`/api/market/options?${queryParams.toString()}`, {
		method: 'GET',
		headers: JSON_HEADERS
	});
}

// 상품 (석유/금/배출권)
export async function fetchMarketCommodities(params: { market?: CommodityMarketName; date?: string; page?: number }): Promise<ResultDto<CommoditiesResponse>>
{
	const queryParams = new URLSearchParams();

	if (params.market) queryParams.set('market', params.market);
	if (params.date) queryParams.set('date', params.date);
	queryParams.set('page', String(params.page ?? 1));

	return await fetchJson<CommoditiesResponse>(`/api/market/commodities?${queryParams.toString()}`, {
		method: 'GET',
		headers: JSON_HEADERS
	});
}

// ESG 증권
export async function fetchMarketEsgSecurities(params: { date?: string; page?: number }): Promise<ResultDto<EsgSecuritiesResponse>>
{
	const queryParams = new URLSearchParams();

	if (params.date) queryParams.set('date', params.date);
	queryParams.set('page', String(params.page ?? 1));

	return await fetchJson<EsgSecuritiesResponse>(`/api/market/esg/securities?${queryParams.toString()}`, {
		method: 'GET',
		headers: JSON_HEADERS
	});
}

// ESG 지수
export async function fetchMarketEsgIndices(params: { date?: string; page?: number }): Promise<ResultDto<EsgIndicesResponse>>
{
	const queryParams = new URLSearchParams();

	if (params.date) queryParams.set('date', params.date);
	queryParams.set('page', String(params.page ?? 1));

	return await fetchJson<EsgIndicesResponse>(`/api/market/esg/indices?${queryParams.toString()}`, {
		method: 'GET',
		headers: JSON_HEADERS
	});
}

// SRI 채권 (사회책임투자채권)
export async function fetchMarketSriBonds(params: { date?: string; bondType?: string; page?: number }): Promise<ResultDto<SriBondsResponse>>
{
	const queryParams = new URLSearchParams();

	if (params.date) queryParams.set('date', params.date);
	if (params.bondType) queryParams.set('bondType', params.bondType);
	queryParams.set('page', String(params.page ?? 1));

	return await fetchJson<SriBondsResponse>(`/api/market/esg/sri-bonds?${queryParams.toString()}`, {
		method: 'GET',
		headers: JSON_HEADERS
	});
}

// 환율 (매매기준율)
export async function fetchMarketExchangeRates(params: { date?: string }): Promise<ResultDto<ExchangeRatesResponse>>
{
	const queryParams = new URLSearchParams();

	if (params.date) queryParams.set('date', params.date);

	const qs = queryParams.toString();

	return await fetchJson<ExchangeRatesResponse>(`/api/market/exchange-rates${qs ? `?${qs}` : ''}`, {
		method: 'GET',
		headers: JSON_HEADERS
	});
}

// 금리 (대출/국제)
export async function fetchMarketInterestRates(params: { type?: RateTypeName; date?: string }): Promise<ResultDto<InterestRatesResponse>>
{
	const queryParams = new URLSearchParams();

	if (params.type) queryParams.set('type', params.type);
	if (params.date) queryParams.set('date', params.date);

	const qs = queryParams.toString();

	return await fetchJson<InterestRatesResponse>(`/api/market/interest-rates${qs ? `?${qs}` : ''}`, {
		method: 'GET',
		headers: JSON_HEADERS
	});
}

// 공시 피드 (전체 — corpCls: Y/K/N/E 필터, 페이징). 경로는 /api/disclosures (market 하위 아님)
export async function fetchDisclosures(params: { corpCls?: string; page?: number }): Promise<ResultDto<DisclosuresResponse>>
{
	const queryParams = new URLSearchParams();

	if (params.corpCls) queryParams.set('corpCls', params.corpCls);
	queryParams.set('page', String(params.page ?? 1));

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

// 종목별 공시 (6자리 코드) — /api/stocks/{code}/disclosures
export async function fetchStockDisclosures(code: string, params: { page?: number }): Promise<ResultDto<DisclosuresResponse>>
{
	const queryParams = new URLSearchParams();

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

	return await fetchJson<DisclosuresResponse>(`/api/stocks/${encodeURIComponent(code)}/disclosures?${queryParams.toString()}`, {
		method: 'GET',
		headers: JSON_HEADERS
	});
}
