import { apiFetch } from '../../utils/apiFetch'
import type { LeaderboardEntry } from '../leaderboard/leaderboardApi'

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

export type GroupDto = {
  id: number
  name: string
  competitionId: number
  competitionName: string
  inviteCode: string
  memberCount: number
  isOwner: boolean
}

export async function fetchGroups(token: string, competitionId: number): Promise<GroupDto[]> {
  const response = await apiFetch(`${apiBaseUrl}/api/group?competitionId=${competitionId}`, {
    headers: { Authorization: `Bearer ${token}` },
  })
  if (!response.ok) throw new Error(`Failed to fetch groups (${response.status})`)
  return response.json() as Promise<GroupDto[]>
}

export async function createGroup(
  token: string,
  name: string,
  competitionId: number,
): Promise<GroupDto> {
  const response = await apiFetch(`${apiBaseUrl}/api/group`, {
    method: 'POST',
    headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
    body: JSON.stringify({ name, competitionId }),
  })
  if (!response.ok) throw new Error(`Failed to create group (${response.status})`)
  return response.json() as Promise<GroupDto>
}

export async function joinGroup(token: string, inviteCode: string): Promise<GroupDto> {
  const response = await apiFetch(`${apiBaseUrl}/api/group/join/${encodeURIComponent(inviteCode)}`, {
    method: 'POST',
    headers: { Authorization: `Bearer ${token}` },
  })
  if (response.status === 409) throw new Error('You are already a member of this group.')
  if (response.status === 404) throw new Error('Group not found. Check the invite code.')
  if (!response.ok) throw new Error(`Failed to join group (${response.status})`)
  return response.json() as Promise<GroupDto>
}

export async function leaveGroup(token: string, groupId: number): Promise<void> {
  const response = await apiFetch(`${apiBaseUrl}/api/group/${groupId}/leave`, {
    method: 'DELETE',
    headers: { Authorization: `Bearer ${token}` },
  })
  if (response.status === 409) throw new Error('Owner cannot leave — delete the group instead.')
  if (!response.ok) throw new Error(`Failed to leave group (${response.status})`)
}

export async function deleteGroup(token: string, groupId: number): Promise<void> {
  const response = await apiFetch(`${apiBaseUrl}/api/group/${groupId}`, {
    method: 'DELETE',
    headers: { Authorization: `Bearer ${token}` },
  })
  if (!response.ok) throw new Error(`Failed to delete group (${response.status})`)
}

export async function fetchGroupLeaderboard(
  token: string,
  groupId: number,
): Promise<LeaderboardEntry[]> {
  const response = await apiFetch(`${apiBaseUrl}/api/group/${groupId}/leaderboard`, {
    headers: { Authorization: `Bearer ${token}` },
  })
  if (!response.ok) throw new Error(`Failed to fetch group leaderboard (${response.status})`)
  return response.json() as Promise<LeaderboardEntry[]>
}
