import request from "@/utils/request";

export interface PresetComment {
  id: number;
  /** 可能为 null（库表允许活动为空） */
  contestId: number | null;
  judgeId: number;
  content: string;
  score?: number;
  sortOrder: number;
  useCount: number;
  validState?: number;
  creator?: number;
  modifier?: number;
  createTime?: string;
  modifyTime?: string;
}

/** 统一列表项字段类型，避免后端 Long/字符串与表格展示不一致 */
function normalizePresetCommentRow(raw: Record<string, unknown>): PresetComment {
  return {
    id: Number(raw.id),
    contestId:
      raw.contestId === undefined || raw.contestId === null
        ? null
        : Number(raw.contestId),
    judgeId: Number(raw.judgeId ?? 0),
    content: String(raw.content ?? ""),
    score: raw.score != null ? Number(raw.score) : undefined,
    sortOrder: Number(raw.sortOrder ?? 0),
    useCount: Number(raw.useCount ?? 0),
    validState: raw.validState != null ? Number(raw.validState) : undefined,
    createTime: raw.createTime as string | undefined,
    modifyTime: raw.modifyTime as string | undefined,
  };
}

export interface CreatePresetCommentParams {
  /** 不传或为 null 表示全局模板（跨活动） */
  contestId?: number | null;
  content: string;
  score?: number;
  sortOrder?: number;
}

export interface UpdatePresetCommentParams {
  content?: string;
  score?: number;
  sortOrder?: number;
}

/** 列表：不带 query，按当前登录评委返回全部预设评语（与评审弹窗「选择评语」一致） */
export async function getPresetCommentsList(): Promise<PresetComment[]> {
  const response = await request.get<any, Record<string, unknown>[]>(
    "/contests/preset-comments"
  );
  const list = Array.isArray(response) ? response : [];
  return list.map((row) => normalizePresetCommentRow(row));
}

// 获取单个预设评语详情
export async function getPresetCommentDetail(
  id: number
): Promise<PresetComment> {
  const response = await request.get<any, PresetComment>(
    `/contests/preset-comments/${id}`
  );
  return response;
}

// 创建预设评语
export async function createPresetComment(
  data: CreatePresetCommentParams
): Promise<PresetComment> {
  const response = await request.post<any, PresetComment>(
    "/contests/preset-comments",
    data
  );
  return response;
}

// 更新预设评语
export async function updatePresetComment(
  id: number,
  data: UpdatePresetCommentParams
): Promise<PresetComment> {
  const response = await request.patch<any, PresetComment>(
    `/contests/preset-comments/${id}`,
    data
  );
  return response;
}

// 删除预设评语
export async function deletePresetComment(id: number): Promise<void> {
  return await request.delete<any, void>(`/contests/preset-comments/${id}`);
}

// 批量删除预设评语
export async function batchDeletePresetComments(ids: number[]): Promise<void> {
  return await request.post<any, void>("/contests/preset-comments/batch-delete", {
    ids,
  });
}

// 增加使用次数
export async function incrementUseCount(id: number): Promise<PresetComment> {
  const response = await request.post<any, PresetComment>(
    `/contests/preset-comments/${id}/use`
  );
  return response;
}

// 兼容性导出：保留 presetCommentsApi 对象
export const presetCommentsApi = {
  getList: getPresetCommentsList,
  getDetail: getPresetCommentDetail,
  create: createPresetComment,
  update: updatePresetComment,
  delete: deletePresetComment,
  batchDelete: batchDeletePresetComments,
  incrementUseCount: incrementUseCount,
};
