'use server';

import { ResultDto } from '@/types/response/common';
import {
	DividendCalendarResponse,
	LockupCalendarResponse,
	MeetingCalendarResponse,
	ElsRiskResponse,
	ForeignCustodyResponse,
	StockDividendsResponse,
	LendingHistoryResponse,
	CbExercisesResponse,
	BondDetailResponse
} from '@/types/seibro';
import { fetchJson } from '@/lib/utils/server';

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

// 배당 캘린더 (권리기준일 from/to 기간 · 페이징)
export async function fetchDividendCalendar(params: { from?: string; to?: string; page?: number; perPage?: number }): Promise<ResultDto<DividendCalendarResponse>>
{
	const queryParams = new URLSearchParams();

	if (params.from) queryParams.set('from', params.from);
	if (params.to) queryParams.set('to', params.to);
	queryParams.set('page', String(params.page ?? 1));
	if (params.perPage) queryParams.set('perPage', String(params.perPage));

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

// 락업(보호예수) 캘린더 (예수일/반환일 from/to 기간 · 페이징)
export async function fetchLockupCalendar(params: { from?: string; to?: string; page?: number; perPage?: number }): Promise<ResultDto<LockupCalendarResponse>>
{
	const queryParams = new URLSearchParams();

	if (params.from) queryParams.set('from', params.from);
	if (params.to) queryParams.set('to', params.to);
	queryParams.set('page', String(params.page ?? 1));
	if (params.perPage) queryParams.set('perPage', String(params.perPage));

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

// 주총 캘린더 (총회일 from/to 기간 · 페이징)
export async function fetchMeetingCalendar(params: { from?: string; to?: string; page?: number; perPage?: number }): Promise<ResultDto<MeetingCalendarResponse>>
{
	const queryParams = new URLSearchParams();

	if (params.from) queryParams.set('from', params.from);
	if (params.to) queryParams.set('to', params.to);
	queryParams.set('page', String(params.page ?? 1));
	if (params.perPage) queryParams.set('perPage', String(params.perPage));

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

// ELS 리스크보드 (기초자산·종목구분·기간 필터 — 기초자산별 시계열 묶음)
export async function fetchElsRisk(params: { bassetCd?: string; secnTpcd?: string; from?: string; to?: string }): Promise<ResultDto<ElsRiskResponse>>
{
	const queryParams = new URLSearchParams();

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

	const qs = queryParams.toString();

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

// 외화 커스터디 (국가·종목구분·기간 필터 — 국가별 시계열 묶음)
export async function fetchForeignCustody(params: { nation?: string; secnTpcd?: string; from?: string; to?: string }): Promise<ResultDto<ForeignCustodyResponse>>
{
	const queryParams = new URLSearchParams();

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

	const qs = queryParams.toString();

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

// 종목 배당 이력 (6자리 단축코드 · 페이징)
export async function fetchStockDividends(code: string, params: { page?: number; perPage?: number }): Promise<ResultDto<StockDividendsResponse>>
{
	const queryParams = new URLSearchParams();

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

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

// 종목 대차 시계열 (6자리 단축코드 · 기간 · 페이징)
export async function fetchStockLending(code: string, params: { from?: string; to?: string; page?: number; perPage?: number }): Promise<ResultDto<LendingHistoryResponse>>
{
	const queryParams = new URLSearchParams();

	if (params.from) queryParams.set('from', params.from);
	if (params.to) queryParams.set('to', params.to);
	queryParams.set('page', String(params.page ?? 1));
	if (params.perPage) queryParams.set('perPage', String(params.perPage));

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

// 종목 CB/BW 행사 내역 (6자리 단축코드 · byBond · 페이징)
export async function fetchStockCbExercises(code: string, params: { byBond?: boolean; page?: number; perPage?: number }): Promise<ResultDto<CbExercisesResponse>>
{
	const queryParams = new URLSearchParams();

	if (params.byBond) queryParams.set('byBond', 'true');
	queryParams.set('page', String(params.page ?? 1));
	if (params.perPage) queryParams.set('perPage', String(params.perPage));

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

// 채권 상세 (12자리 ISIN)
export async function fetchBondDetail(isin: string): Promise<ResultDto<BondDetailResponse>>
{
	return await fetchJson<BondDetailResponse>(`/api/stocks/bonds/${encodeURIComponent(isin)}`, {
		method: 'GET',
		headers: JSON_HEADERS
	});
}
