import type { TeamResponse } from '../teams/teamApi'
import { apiFetch } from '../../utils/apiFetch'

export type { TeamResponse }

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

export type MatchResponse = {
  id: number
  competitionId: number
  homeTeam: TeamResponse
  awayTeam: TeamResponse
  matchDate: string
  round: string
  homeScore: number | null
  awayScore: number | null
}

export type CreateMatchRequest = {
  competitionId: number
  homeTeamId: number
  awayTeamId: number
  matchDate: string
  round: string
}

export type UpdateMatchRequest = {
  competitionId: number
  homeTeamId: number
  awayTeamId: number
  matchDate: string
  round: string
  homeScore: number | null
  awayScore: number | null
}

export async function fetchPendingResults(token: string): Promise<MatchResponse[]> {
  const response = await apiFetch(`${apiBaseUrl}/api/match/pending-results`, {
    headers: { Authorization: `Bearer ${token}` },
  })

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

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

export async function fetchMatches(token: string, competitionId: number): Promise<MatchResponse[]> {
  const response = await apiFetch(`${apiBaseUrl}/api/match?competitionId=${competitionId}`, {
    headers: { Authorization: `Bearer ${token}` },
  })

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

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

export async function createMatch(token: string, dto: CreateMatchRequest): Promise<MatchResponse> {
  const response = await apiFetch(`${apiBaseUrl}/api/match`, {
    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 match (${response.status})`)
  }

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

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

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

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