import { cowHttp, frogHttp, sharkHttp } from '@/lib/http/instances'
import type {
  FetchAiUserLikedRequest,
  FetchImageCheckRequest,
  FetchImageCheckResponse,
  FetchS3StsTokenRequest,
  FetchS3StsTokenResponse,
  FetchVoiceTtsV2Request,
  FetchVoiceTtsV2Response,
} from './types'

export const authService = {
  // 获取s3的sts的授权token
  fetchS3StsToken: (data: FetchS3StsTokenRequest): Promise<FetchS3StsTokenResponse> => {
    return sharkHttp.post('/web/file/sts-tk', data)
  },

  fetchImageCheck: (data: FetchImageCheckRequest): Promise<FetchImageCheckResponse> => {
    return sharkHttp.post('/web/file/check', data)
  },

  fetchVoiceTtsV2: async (data: FetchVoiceTtsV2Request): Promise<Blob> => {
    const response: FetchVoiceTtsV2Response | string = await cowHttp.post(
      '/web/voice/tts-v2',
      data,
      { ignoreError: true }
    )

    // 假设接口返回的是base64编码的MP3数据
    // 如果返回的是 { data: "base64_encoded_audio" } 或者直接是base64字符串
    let base64Data: string

    if (typeof response === 'string') {
      // 直接返回base64字符串
      base64Data = response
    } else if (response && typeof response === 'object' && 'data' in response) {
      // 返回对象包含data字段
      base64Data = response.data || ''
    } else {
      throw new Error('Invalid response format from TTS API')
    }

    if (!base64Data) {
      throw new Error('No audio data received from TTS API')
    }

    // 去除可能的data:audio/mp3;base64,前缀
    const cleanBase64 = base64Data.replace(/^data:audio\/[^;]+;base64,/, '')

    // 将base64转换为Blob
    try {
      const binaryString = atob(cleanBase64)
      const bytes = new Uint8Array(binaryString.length)
      for (let i = 0; i < binaryString.length; i++) {
        bytes[i] = binaryString.charCodeAt(i)
      }

      return new Blob([bytes], { type: 'audio/mp3' })
    } catch (error) {
      throw new Error('Failed to decode base64 audio data: ' + error)
    }
  },

  doAiUserLiked: (data: FetchAiUserLikedRequest): Promise<void> => {
    return frogHttp.post('/web/ai-user/like-or-cancel', data)
  },
}
