import client from './client'
import type { SpinResult, Assignment, CompleteResult, DropResult } from '@/types'

export const wheelApi = {
  spin: async (marathonId: number): Promise<SpinResult> => {
    const response = await client.post<SpinResult>(`/marathons/${marathonId}/spin`)
    return response.data
  },

  getCurrentAssignment: async (marathonId: number): Promise<Assignment | null> => {
    const response = await client.get<Assignment | null>(`/marathons/${marathonId}/current-assignment`)
    return response.data
  },

  complete: async (
    assignmentId: number,
    data: { proof_url?: string; comment?: string; proof_file?: File; proof_files?: File[] }
  ): Promise<CompleteResult> => {
    const formData = new FormData()
    if (data.proof_url) formData.append('proof_url', data.proof_url)
    if (data.comment) formData.append('comment', data.comment)

    // Support both single file (legacy) and multiple files
    if (data.proof_file) formData.append('proof_file', data.proof_file)
    if (data.proof_files && data.proof_files.length > 0) {
      data.proof_files.forEach(file => {
        formData.append('proof_files', file)
      })
    }

    const response = await client.post<CompleteResult>(`/assignments/${assignmentId}/complete`, formData, {
      headers: { 'Content-Type': 'multipart/form-data' },
    })
    return response.data
  },

  drop: async (assignmentId: number): Promise<DropResult> => {
    const response = await client.post<DropResult>(`/assignments/${assignmentId}/drop`)
    return response.data
  },

  getHistory: async (marathonId: number, limit = 20, offset = 0): Promise<Assignment[]> => {
    const response = await client.get<Assignment[]>(`/marathons/${marathonId}/my-history`, {
      params: { limit, offset },
    })
    return response.data
  },
}
