import { apiFetch } from '../../utils/apiFetch'

const apiBaseUrl = import.meta.env.VITE_API_URL ?? 'http://localhost:5000'

export type CompetitionResponse = {
  id: number
  name: string
  startDate: string
  endDate: string
  description: string
  logoUrl?: string | null
}

export async function fetchCompetitions(token: string): Promise<CompetitionResponse[]> {
  const response = await apiFetch(`${apiBaseUrl}/api/competition`, {
    headers: { Authorization: `Bearer ${token}` },
  })

  if (!response.ok) {
    throw new Error(`Failed to fetch competitions (${response.status})`)
  }

  return response.json() as Promise<CompetitionResponse[]>
}

export type CreateCompetitionRequest = {
  name: string
  startDate: string
  endDate: string
  description: string
}

export async function createCompetition(token: string, dto: CreateCompetitionRequest): Promise<CompetitionResponse> {
  const response = await apiFetch(`${apiBaseUrl}/api/competition`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
    body: JSON.stringify(dto),
  })

  if (!response.ok) {
    const data = (await response.json()) as { message?: string } | undefined
    throw new Error(data?.message ?? `Failed to create competition (${response.status})`)
  }

  return response.json() as Promise<CompetitionResponse>
}

export async function updateCompetition(token: string, id: number, dto: CreateCompetitionRequest): Promise<CompetitionResponse> {
  const response = await apiFetch(`${apiBaseUrl}/api/competition/${id}`, {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
    body: JSON.stringify(dto),
  })

  if (!response.ok) {
    const data = (await response.json()) as { message?: string } | undefined
    throw new Error(data?.message ?? `Failed to update competition (${response.status})`)
  }

  return response.json() as Promise<CompetitionResponse>
}

export async function deleteCompetition(token: string, id: number): Promise<void> {
  const response = await apiFetch(`${apiBaseUrl}/api/competition/${id}`, {
    method: 'DELETE',
    headers: { Authorization: `Bearer ${token}` },
  })

  if (!response.ok) {
    const data = (await response.json()) as { message?: string } | undefined
    throw new Error(data?.message ?? `Failed to delete competition (${response.status})`)
  }
}

export async function uploadCompetitionLogo(token: string, id: number, file: File): Promise<CompetitionResponse> {
  const formData = new FormData()
  formData.append('file', file)

  const response = await apiFetch(`${apiBaseUrl}/api/competition/${id}/logo`, {
    method: 'POST',
    headers: { Authorization: `Bearer ${token}` },
    body: formData,
  })

  if (!response.ok) {
    const data = (await response.json()) as { message?: string } | undefined
    throw new Error(data?.message ?? `Failed to upload competition logo (${response.status})`)
  }

  return response.json() as Promise<CompetitionResponse>
}

export function competitionLogoUrl(logoUrl: string | null | undefined): string | undefined {
  if (!logoUrl) return undefined
  return `${apiBaseUrl}${logoUrl}`
}
