import { ndmClient, userClient, type HighAvailable, type MediaServerStatus, type SendRtpInfo, type Station } from '@/apis';
import { unwrapNullableResponse, unwrapResponse } from '@/utils';
import destr from 'destr';

// {
//   "code": 0,
//   "data": "{pyip:\"10.18.128.14\",vip:\"10.18.128.6\",changeDate:\"2026-03-23 15:55:00\"}",
//   "msg": "ok",
//   "path": null,
//   "extra": null,
//   "timestamp": "1774421387908",
//   "errorMsg": "",
//   "isSuccess": true
// }
export const getHighAvailableApi = async (options?: { stationCode?: Station['code']; signal?: AbortSignal }) => {
  const { stationCode, signal } = options ?? {};
  const client = stationCode ? ndmClient : userClient;
  const prefix = stationCode ? `/${stationCode}` : '';
  const endpoint = `${prefix}/api/ndm/ndmServiceAvailable/highAvailable/get`;
  const resp = await client.get<string | null>(endpoint, { signal });
  const data = unwrapNullableResponse(resp);
  return destr<HighAvailable | null>(data);
};

export const getAllPushApi = async (options?: { stationCode?: Station['code']; signal?: AbortSignal }) => {
  const { stationCode, signal } = options ?? {};
  const client = stationCode ? ndmClient : userClient;
  const prefix = stationCode ? `/${stationCode}` : '';
  const endpoint = `${prefix}/api/ndm/ndmServiceAvailable/mediaServer/getAllPush`;
  const resp = await client.get<SendRtpInfo[]>(endpoint, { signal });
  const data = unwrapResponse(resp);
  return data;
};

export const isMediaServerAliveApi = async (options?: { stationCode?: Station['code']; signal?: AbortSignal }) => {
  const { stationCode, signal } = options ?? {};
  const client = stationCode ? ndmClient : userClient;
  const prefix = stationCode ? `/${stationCode}` : '';
  const endpoint = `${prefix}/api/ndm/ndmServiceAvailable/mediaServer/isAlive`;
  const resp = await client.get<MediaServerStatus[]>(endpoint, { signal });
  const data = unwrapResponse(resp);
  return data;
};

export const isSipServerAliveApi = async (options?: { stationCode?: Station['code']; signal?: AbortSignal }) => {
  const { stationCode, signal } = options ?? {};
  const client = stationCode ? ndmClient : userClient;
  const prefix = stationCode ? `/${stationCode}` : '';
  const endpoint = `${prefix}/api/ndm/ndmServiceAvailable/sipServer/isAlive`;
  const resp = await client.get<boolean>(endpoint, { signal });
  const data = unwrapResponse(resp);
  return data;
};
