import client from './client'
import type { AssignmentDetail, Dispute, DisputeComment, ReturnedAssignment } from '@/types'

export const assignmentsApi = {
  // Get detailed assignment info with proofs and dispute
  getDetail: async (assignmentId: number): Promise<AssignmentDetail> => {
    const response = await client.get<AssignmentDetail>(`/assignments/${assignmentId}`)
    return response.data
  },

  // Create a dispute against an assignment
  createDispute: async (assignmentId: number, reason: string): Promise<Dispute> => {
    const response = await client.post<Dispute>(`/assignments/${assignmentId}/dispute`, { reason })
    return response.data
  },

  // Add a comment to a dispute
  addComment: async (disputeId: number, text: string): Promise<DisputeComment> => {
    const response = await client.post<DisputeComment>(`/disputes/${disputeId}/comments`, { text })
    return response.data
  },

  // Vote on a dispute (true = valid/proof is OK, false = invalid/proof is not OK)
  vote: async (disputeId: number, vote: boolean): Promise<{ message: string }> => {
    const response = await client.post<{ message: string }>(`/disputes/${disputeId}/vote`, { vote })
    return response.data
  },

  // Get current user's returned assignments
  getReturnedAssignments: async (marathonId: number): Promise<ReturnedAssignment[]> => {
    const response = await client.get<ReturnedAssignment[]>(`/marathons/${marathonId}/returned-assignments`)
    return response.data
  },

  // Get proof media as blob URL (supports both images and videos)
  getProofMediaUrl: async (assignmentId: number): Promise<{ url: string; type: 'image' | 'video' }> => {
    const response = await client.get(`/assignments/${assignmentId}/proof-media`, {
      responseType: 'blob',
    })
    const contentType = response.headers['content-type'] || ''
    const isVideo = contentType.startsWith('video/')
    return {
      url: URL.createObjectURL(response.data),
      type: isVideo ? 'video' : 'image',
    }
  },
}
