import { SYSTEM_SERVICE_PREFIX } from '@/constants/service';
import { request } from '../request';
import { type ServiceRequestResult, mapServiceResult, normalizeStringId, safeJsonRequestConfig } from './shared';

const NOTIFY_MESSAGE_PREFIX = `${SYSTEM_SERVICE_PREFIX}/notify-message`;

type NotifyMessageResponse = Omit<Api.NotifyMessage.NotifyMessage, 'id' | 'level'> & {
  id: string | number;
  /** 后端老消息可能不带 level，按可空接收，normalize 时回落普通(1) */
  level?: number | null;
};

type MyNotifyMessagePageResponse = Omit<Api.NotifyMessage.PageResult<Api.NotifyMessage.NotifyMessage>, 'list'> & {
  list: NotifyMessageResponse[];
};

function normalizeNotifyMessage(data: NotifyMessageResponse): Api.NotifyMessage.NotifyMessage {
  return {
    ...data,
    id: normalizeStringId(data.id),
    level: data.level ?? 1
  };
}

/** 获取当前用户未读站内信数量（铃铛红点轮询用） */
export function fetchGetUnreadNotifyCount() {
  return request<number>({
    url: `${NOTIFY_MESSAGE_PREFIX}/get-unread-count`,
    method: 'get'
  });
}

/** 分页获取我的站内信（消息列表唯一数据源；未读传 readStatus=false、已读传 true） */
export async function fetchGetMyNotifyMessagePage(params: Api.NotifyMessage.MyPageParams) {
  const result = await request<MyNotifyMessagePageResponse>({
    url: `${NOTIFY_MESSAGE_PREFIX}/my-page`,
    method: 'get',
    params,
    ...safeJsonRequestConfig
  });

  return mapServiceResult(result as ServiceRequestResult<MyNotifyMessagePageResponse>, data => ({
    ...data,
    list: data.list.map(normalizeNotifyMessage)
  }));
}

/** 批量标记站内信已读（后端幂等：重复提交、非本人条目均安全） */
export function fetchUpdateNotifyMessageRead(ids: string[]) {
  // 后端约定 ids 逗号分隔
  return request<boolean>({
    url: `${NOTIFY_MESSAGE_PREFIX}/update-read?ids=${ids.join(',')}`,
    method: 'put'
  });
}

/** 当前用户全部站内信标记已读 */
export function fetchUpdateAllNotifyMessageRead() {
  return request<boolean>({
    url: `${NOTIFY_MESSAGE_PREFIX}/update-all-read`,
    method: 'put'
  });
}
