import request from '@/utils/http'

const GROUP_BASE_URL = '/api/admin/v1/dictionary/groups'

export function getGroups(params?: Api.Dictionary.DictionaryGroupQueryParams) {
  return request.get<Api.Common.PageResult<Api.Dictionary.DictionaryGroupDto>>({
    url: GROUP_BASE_URL,
    params
  })
}

export function getGroupById(groupId: string) {
  return request.get<Api.Dictionary.DictionaryGroupDto>({
    url: `${GROUP_BASE_URL}/${groupId}`
  })
}

export function createGroup(data: Api.Dictionary.CreateDictionaryGroupRequest) {
  return request.post<Api.Dictionary.DictionaryGroupDto>({
    url: GROUP_BASE_URL,
    data
  })
}

export function updateGroup(groupId: string, data: Api.Dictionary.UpdateDictionaryGroupRequest) {
  return request.put<Api.Dictionary.DictionaryGroupDto>({
    url: `${GROUP_BASE_URL}/${groupId}`,
    data
  })
}

export function deleteGroup(groupId: string) {
  return request.del<void>({
    url: `${GROUP_BASE_URL}/${groupId}`
  })
}

export function exportGroup(
  groupId: string,
  format: Api.Dictionary.DictionaryExportRequest['format']
) {
  return request.post<Blob>({
    url: `${GROUP_BASE_URL}/${groupId}/export`,
    data: { format },
    responseType: 'blob'
  })
}

export function importGroup(
  groupId: string,
  payload: {
    file: File
    conflictMode?: Api.Dictionary.ConflictResolutionMode | string
    format?: 'csv' | 'json'
  }
) {
  const formData = new FormData()
  formData.append('File', payload.file)
  if (payload.conflictMode) {
    formData.append('ConflictMode', String(payload.conflictMode))
  }
  if (payload.format) {
    formData.append('Format', payload.format)
  }

  return request.post<Api.Dictionary.DictionaryImportResultDto>({
    url: `${GROUP_BASE_URL}/${groupId}/import`,
    data: formData
  })
}
