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

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

export type TeamResponse = {
  id: number
  name: string
  logoUrl?: string | null
}

export async function fetchTeams(token: string, competitionId?: number): Promise<TeamResponse[]> {
  const url = competitionId != null
    ? `${apiBaseUrl}/api/team?competitionId=${competitionId}`
    : `${apiBaseUrl}/api/team`
  const response = await apiFetch(url, {
    headers: { Authorization: `Bearer ${token}` },
  })

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

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

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

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

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

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

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

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

export async function deleteTeam(token: string, id: number): Promise<void> {
  const response = await apiFetch(`${apiBaseUrl}/api/team/${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 team (${response.status})`)
  }
}

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

  const response = await apiFetch(`${apiBaseUrl}/api/team/${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 team logo (${response.status})`)
  }

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

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