import type {
  RequestResult,
  SkillFileContent,
  SkillFileNode,
  SkillImportPreview,
  SkillInfo,
} from './types';

import {api} from '#/api/request';

export function getSkillDetail(id: number | string) {
  return api.get<RequestResult<SkillInfo>>('/api/v1/skill/getDetail', {
    params: { id },
  });
}

export function saveSkill(skill: SkillInfo) {
  return api.post<RequestResult<SkillInfo>>('/api/v1/skill/save', skill);
}

export function updateSkill(skill: SkillInfo) {
  return api.post<RequestResult<SkillInfo>>('/api/v1/skill/update', skill);
}

export function getSkillCategories() {
  return api.get<RequestResult<any[]>>('/api/v1/skillCategory/visibleList', {
    params: { sortKey: 'sortNo', sortType: 'asc' },
  });
}

export function submitSkillPublishApproval(id: number | string) {
  return api.post<RequestResult<number | string>>(
    '/api/v1/skill/submitPublishApproval',
    { id },
  );
}

export function submitSkillOfflineApproval(id: number | string) {
  return api.post<RequestResult<number | string>>(
    '/api/v1/skill/submitOfflineApproval',
    { id },
  );
}

export function submitSkillDeleteApproval(id: number | string) {
  return api.post<RequestResult<number | string>>(
    '/api/v1/skill/submitDeleteApproval',
    { id },
  );
}

export function getSkillFileTree(skillId: number | string) {
  return api.get<RequestResult<SkillFileNode[]>>('/api/v1/skill/file/tree', {
    params: { skillId },
  });
}

export function getSkillFileContent(skillId: number | string, path: string) {
  return api.get<RequestResult<SkillFileContent>>('/api/v1/skill/file/content', {
    params: { skillId, path },
  });
}

export function saveSkillFile(
  skillId: number | string,
  path: string,
  content: string,
) {
  return api.post<RequestResult<SkillFileContent>>('/api/v1/skill/file/save', {
    skillId,
    path,
    content,
  });
}

export function importSkillPreview(file: File) {
  const formData = new FormData();
  formData.append('file', file);
  return api.postFile<RequestResult<SkillImportPreview>>(
    '/api/v1/skill/import/preview',
    formData,
  );
}

export function importSkillConfirm(
  file: File,
  categoryId?: number | string,
  overwriteDraft = false,
) {
  const formData = new FormData();
  formData.append('file', file);
  if (categoryId) {
    formData.append('categoryId', String(categoryId));
  }
  formData.append('overwriteDraft', String(overwriteDraft));
  return api.postFile<RequestResult<SkillInfo[]>>(
    '/api/v1/skill/import/confirm',
    formData,
  );
}

export function resolveSkillAssetUrl(skillId: number | string, path: string) {
  return `/api/v1/skill/file/asset?skillId=${encodeURIComponent(
    String(skillId),
  )}&path=${encodeURIComponent(path)}`;
}
