// components/video-player/composables/useVideoAPI.ts
import { ref } from 'vue'
import { videoApi } from '@/api/modules/video'
import type { IVideoInfo, VideoErrorType } from '@/types/video'

/**
 * 视频 API 调用管理
 */
export function useVideoAPI() {
  const isLoading = ref(false)
  const error = ref<{ type: VideoErrorType; message: string } | null>(null)

  /**
   * 获取视频播放信息
   */
  const fetchVideoInfo = async (params: {
    id: number
  }): Promise<IVideoInfo | null> => {
    isLoading.value = true
    error.value = null

    try {
      const response = await videoApi.checkVideo(params)

      if (response.code === 0 && response.video) {
        console.log('Video info fetched:', response.video)
        return response.video
      } else {
        throw new Error(response.msg || '获取视频信息失败')
      }
    } catch (err: any) {
      console.error('Failed to fetch video info:', err)
      error.value = {
        type: 'API_ERROR' as VideoErrorType,
        message: err.message || '获取视频信息失败，请稍后重试'
      }
      return null
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 报告错误视频
   */
  const reportErrorVideo = async (params: {
    chapterId: number
    videoId: number
    sort: number
  }): Promise<void> => {
    try {
      await videoApi.addErrorCourse(params)
      console.log('Error video reported:', params)
    } catch (err) {
      console.error('Failed to report error video:', err)
    }
  }

  /**
   * 清除错误
   */
  const clearError = () => {
    error.value = null
  }

  return {
    isLoading,
    error,
    fetchVideoInfo,
    reportErrorVideo,
    clearError
  }
}
