import { authedRequest, type AuthSession } from './authed-request'

export interface RoomItem {
  room_id: string
  name: string
  game_type: string
  owner_id: string
  max_players: number
  player_count: number
  players?: Array<{
    index: number
    player_id: string
    player_name?: string
    PlayerName?: string
    ready: boolean
  }>
  status: string
  created_at: string
  updated_at: string
}

export interface RoomListResult {
  items: RoomItem[]
  page: number
  size: number
  total: number
}

const ROOM_CREATE_PATH =
  import.meta.env.VITE_ROOM_CREATE_PATH ?? '/api/v1/game/mahjong/room/create'
const ROOM_LIST_PATH = import.meta.env.VITE_ROOM_LIST_PATH ?? '/api/v1/game/mahjong/room/list'
const ROOM_JOIN_PATH = import.meta.env.VITE_ROOM_JOIN_PATH ?? '/api/v1/game/mahjong/room/join'

export async function createRoom(
  auth: AuthSession,
  input: { name: string; gameType: string; maxPlayers: number },
  onAuthUpdated?: (next: AuthSession) => void,
): Promise<RoomItem> {
  return authedRequest<RoomItem>({
    method: 'POST',
    path: ROOM_CREATE_PATH,
    auth,
    onAuthUpdated,
    body: {
      name: input.name,
      game_type: input.gameType,
      max_players: input.maxPlayers,
    },
  })
}

export async function listRooms(
  auth: AuthSession,
  onAuthUpdated?: (next: AuthSession) => void,
): Promise<RoomListResult> {
  return authedRequest<RoomListResult>({
    method: 'GET',
    path: ROOM_LIST_PATH,
    auth,
    onAuthUpdated,
  })
}

export async function joinRoom(
  auth: AuthSession,
  input: { roomId: string },
  onAuthUpdated?: (next: AuthSession) => void,
): Promise<RoomItem> {
  return authedRequest<RoomItem>({
    method: 'POST',
    path: ROOM_JOIN_PATH,
    auth,
    onAuthUpdated,
    body: {
      room_id: input.roomId,
    },
  })
}
