import { useApi } from './useApi'
import type {
  ApiProjectMember,
  InviteMemberPayload,
  UpdateMemberPayload,
} from '@/types/member'
import type { Paginated } from '@/types/pagination'

// 프로젝트 멤버 도메인 API Composable — 인터셉터가 success/data 를 언래핑
// 경로는 모두 projectId 하위: /projects/:projectId/members
export function useMember() {
  const api = useApi()

  // 멤버 목록 (멤버 또는 공개 프로젝트) — 백엔드가 페이지네이션 { items, total, ... } 반환
  async function list(
    projectId: string,
    page = 1,
    size = 20,
  ): Promise<Paginated<ApiProjectMember>> {
    return (await api.get(`/projects/${projectId}/members`, {
      params: { page, size },
    })) as unknown as Paginated<ApiProjectMember>
  }

  // 멤버 초대 (admin) — 가입된 사용자만 이메일로 초대
  async function invite(
    projectId: string,
    payload: InviteMemberPayload,
  ): Promise<ApiProjectMember> {
    return (await api.post(
      `/projects/${projectId}/members`,
      payload,
    )) as unknown as ApiProjectMember
  }

  // 멤버 역할/직무 변경 (admin, owner 제외)
  async function update(
    projectId: string,
    userId: string,
    payload: UpdateMemberPayload,
  ): Promise<ApiProjectMember> {
    return (await api.patch(
      `/projects/${projectId}/members/${userId}`,
      payload,
    )) as unknown as ApiProjectMember
  }

  // 멤버 제거 (admin, owner 제외)
  async function remove(projectId: string, userId: string): Promise<void> {
    await api.delete(`/projects/${projectId}/members/${userId}`)
  }

  return { list, invite, update, remove }
}
