import client from './client'
import type {
  WidgetToken,
  WidgetLeaderboardData,
  WidgetCurrentData,
  WidgetProgressData,
} from '../types'

export const widgetsApi = {
  // Authenticated endpoints (for managing tokens)
  createToken: async (marathonId: number): Promise<WidgetToken> => {
    const response = await client.post<WidgetToken>(`/widgets/marathons/${marathonId}/token`)
    return response.data
  },

  listTokens: async (marathonId: number): Promise<WidgetToken[]> => {
    const response = await client.get<WidgetToken[]>(`/widgets/marathons/${marathonId}/tokens`)
    return response.data
  },

  revokeToken: async (tokenId: number): Promise<{ message: string }> => {
    const response = await client.delete<{ message: string }>(`/widgets/tokens/${tokenId}`)
    return response.data
  },

  regenerateToken: async (tokenId: number): Promise<WidgetToken> => {
    const response = await client.post<WidgetToken>(`/widgets/tokens/${tokenId}/regenerate`)
    return response.data
  },

  // Public widget data endpoints (authenticated via widget token)
  getLeaderboard: async (marathonId: number, token: string, count: number = 5): Promise<WidgetLeaderboardData> => {
    const response = await client.get<WidgetLeaderboardData>(
      `/widgets/data/leaderboard?marathon=${marathonId}&token=${token}&count=${count}`
    )
    return response.data
  },

  getCurrent: async (marathonId: number, token: string): Promise<WidgetCurrentData> => {
    const response = await client.get<WidgetCurrentData>(
      `/widgets/data/current?marathon=${marathonId}&token=${token}`
    )
    return response.data
  },

  getProgress: async (marathonId: number, token: string): Promise<WidgetProgressData> => {
    const response = await client.get<WidgetProgressData>(
      `/widgets/data/progress?marathon=${marathonId}&token=${token}`
    )
    return response.data
  },
}
