import { uploadFile } from '../uploadFile'
import { root } from '@repo/core'
import { FileController } from '@repo/sdk'
import { handleError } from '@/hooks/use-error'

jest.mock('@repo/core')
jest.mock('@repo/sdk')
jest.mock('@/hooks/use-error')

describe('uploadFile', () => {
  const mockUploadS3 = jest.fn()
  const mockHandleError = handleError as jest.MockedFunction<typeof handleError>

  beforeEach(() => {
    jest.clearAllMocks()
    ;(root.get as jest.Mock).mockReturnValue({
      uploadS3: mockUploadS3,
    })
  })

  it('应该成功上传文件并返回URL', async () => {
    const mockUrl = 'https://example.com/uploaded-file.jpg'
    mockUploadS3.mockResolvedValue(mockUrl)
    mockHandleError.mockImplementation(async (fn) => {
      const result = await fn()
      return { data: { data: result }, error: null }
    })

    const result = await uploadFile({
      uri: 'file:///path/to/image.jpg',
      mimeType: 'image/jpeg',
      fileName: 'test.jpg',
    })

    expect(result).toBe(mockUrl)
    expect(mockUploadS3).toHaveBeenCalledWith(expect.any(FormData))
  })

  it('应该使用正确的FormData格式', async () => {
    mockUploadS3.mockResolvedValue('https://example.com/file.jpg')
    mockHandleError.mockImplementation(async (fn) => {
      const result = await fn()
      return { data: { data: result }, error: null }
    })

    await uploadFile({
      uri: 'file:///path/to/image.jpg',
      mimeType: 'image/png',
      fileName: 'avatar.png',
    })

    const formDataCall = mockUploadS3.mock.calls[0][0]
    expect(formDataCall).toBeInstanceOf(FormData)
  })

  it('应该在上传失败时抛出错误', async () => {
    const mockError = new Error('网络错误')
    mockHandleError.mockImplementation(async () => {
      return { data: null, error: mockError }
    })

    await expect(
      uploadFile({
        uri: 'file:///path/to/image.jpg',
      })
    ).rejects.toThrow()
  })

  it('应该使用默认文件名和类型', async () => {
    mockUploadS3.mockResolvedValue('https://example.com/file.jpg')
    mockHandleError.mockImplementation(async (fn) => {
      const result = await fn()
      return { data: { data: result }, error: null }
    })

    await uploadFile({
      uri: 'file:///path/to/image.jpg',
    })

    expect(mockUploadS3).toHaveBeenCalled()
  })
})
