import { useApi } from './useApi'
import type {
  ApiMeetingRoom,
  CreateMeetingRoomPayload,
  UpdateMeetingRoomPayload,
} from '@/types/meeting'

// 회의 내 역할 — 진행자(방 생성자) / 일반 참여자
export type MeetingRole = 'host' | 'participant'

// 화상회의 토큰 응답 — 백엔드 MeetingTokenResult 와 1:1
export interface MeetingToken {
  token: string // LiveKit 입장 JWT
  roomName: string
  identity: string // 참여자 식별자(사용자 ID)
  role: MeetingRole // 이번 입장자의 역할
}

// 화상회의 도메인 API Composable — 인터셉터가 success/data 를 언래핑
export function useMeeting() {
  const api = useApi()

  // LiveKit 입장 토큰 발급 — 방 입장 코드로 요청한다.
  async function getToken(code: string): Promise<MeetingToken> {
    return (await api.post('/meetings/token', {
      code,
    })) as unknown as MeetingToken
  }

  // 방 목록
  async function listRooms(): Promise<ApiMeetingRoom[]> {
    return (await api.get('/meetings/rooms')) as unknown as ApiMeetingRoom[]
  }

  // 방 생성(생성자=진행자)
  async function createRoom(
    payload: CreateMeetingRoomPayload,
  ): Promise<ApiMeetingRoom> {
    return (await api.post(
      '/meetings/rooms',
      payload,
    )) as unknown as ApiMeetingRoom
  }

  // 방 수정(진행자만) — 이름·예약·참여 제한 변경
  async function updateRoom(
    roomId: string,
    payload: UpdateMeetingRoomPayload,
  ): Promise<ApiMeetingRoom> {
    return (await api.patch(
      `/meetings/rooms/${roomId}`,
      payload,
    )) as unknown as ApiMeetingRoom
  }

  // 방 삭제(진행자만)
  async function removeRoom(roomId: string): Promise<void> {
    await api.delete(`/meetings/rooms/${roomId}`)
  }

  return { getToken, listRooms, createRoom, updateRoom, removeRoom }
}
