import { editorPath } from '../lib/paths'

export function useAdminTemplateRequests({
  api,
  activeTemplateRequest,
  refreshTemplateRequests,
  setTab,
  openTemplateCreateModal,
  newTemplateId,
  newTemplateName,
  selectAdminTemplate,
  mergeRequestItemsIntoDrafts,
  resetMessages,
  success,
  error,
}) {
  function updateActiveTemplateRequest(request) {
    if (!request?.id) return
    activeTemplateRequest.value = {
      id: request.id,
      type: request.type,
      status: request.status,
      thumbnailSrc: request.thumbnailSrc || '',
      draftTopicId: request.draftTopicId || '',
      draftTopicName: request.draftTopicName || '',
      draftTopicIsPublic: !!request.draftTopicIsPublic,
      sourceTierListId: request.sourceTierListId || '',
      sourceTopicId: request.sourceTopicId || '',
      sourceTopicSlug: request.sourceTopicSlug || '',
      sourceTierListTitle: request.sourceTierListTitle || '',
      targetTopicId: request.targetTopicId || '',
      targetTopicSlug: request.targetTopicSlug || '',
      targetTopicName: request.targetTopicName || '',
      requesterName: request.requesterName || '',
    }
  }

  function templateRequestStatusLabel(request) {
    return request.status === 'reviewing' ? '확인함' : '미확인'
  }

  function templateRequestSourceUrl(request) {
    const topicRef = request?.sourceTopicSlug || request?.sourceTopicId || ''
    if (!topicRef || !request?.sourceTierListId) return ''
    return editorPath(topicRef, request.sourceTierListId, { preview: true })
  }

  function templateRequestReviewHint(request) {
    if (request.type === 'create') return '템플릿 생성 후 필요한 아이템만 골라 추가하고, 끝나면 여기서 처리 완료하세요.'
    return '확인하기를 누르면 템플릿 관리 화면에 요청 아이템이 임시 추가되어 필요한 것만 선별 저장할 수 있어요.'
  }

  async function startTemplateRequestReview(request) {
    resetMessages()
    try {
      request.isHandling = true
      const data = await api.startAdminTemplateRequestReview(request.id)
      const syncedRequest = {
        ...request,
        ...(data.request || {}),
        draftTopicId: request.draftTopicId || '',
        draftTopicName: request.draftTopicName || '',
        draftTopicIsPublic: !!request.draftTopicIsPublic,
      }
      Object.assign(request, syncedRequest)
      request.status = syncedRequest.status || 'reviewing'
      updateActiveTemplateRequest(syncedRequest)
      setTab('template-admin')

      if (request.type === 'create') {
        const linkedTopicId = syncedRequest.targetTopicId || ''
        if (linkedTopicId) {
          await selectAdminTemplate(linkedTopicId)
        } else {
          openTemplateCreateModal()
          newTemplateId.value = (syncedRequest.draftTopicId || '').trim()
          newTemplateName.value = (syncedRequest.draftTopicName || '').trim()
        }
        mergeRequestItemsIntoDrafts(syncedRequest)
      } else {
        const nextTopicId = syncedRequest.targetTopicId || syncedRequest.sourceTopicId || ''
        if (nextTopicId) await selectAdminTemplate(nextTopicId)
        mergeRequestItemsIntoDrafts(syncedRequest)
      }
      success.value = '요청 아이템을 템플릿 관리 화면으로 가져왔어요. 필요한 항목만 골라서 추가해 주세요.'
    } catch (e) {
      error.value = '요청 확인 단계로 이동하지 못했어요.'
    } finally {
      request.isHandling = false
    }
  }

  async function completeTemplateRequest(request) {
    resetMessages()
    try {
      request.isHandling = true
      await api.completeAdminTemplateRequest(request.id)
      if (activeTemplateRequest.value?.id === request.id) activeTemplateRequest.value = null
      await refreshTemplateRequests()
      success.value = '요청 카드를 처리 완료로 정리했어요.'
    } catch (e) {
      error.value = '요청 완료 처리에 실패했어요.'
    } finally {
      request.isHandling = false
    }
  }

  return {
    updateActiveTemplateRequest,
    templateRequestStatusLabel,
    templateRequestSourceUrl,
    templateRequestReviewHint,
    startTemplateRequestReview,
    completeTemplateRequest,
  }
}
