import { queryOptions } from '@tanstack/react-query'
import { api } from '@/lib/api-client'
import type { Member } from '@/types/account'
import type { PaginatedResponse, PaginationInput } from '@lunarfront/shared/schemas'

interface MemberWithAccount extends Member {
  accountName: string | null
}

export const memberKeys = {
  all: (accountId: string) => ['accounts', accountId, 'members'] as const,
  list: (accountId: string, params: PaginationInput) => [...memberKeys.all(accountId), params] as const,
  globalAll: ['members'] as const,
  globalList: (params: PaginationInput) => ['members', 'list', params] as const,
}

export function memberListOptions(accountId: string, params: PaginationInput) {
  return queryOptions({
    queryKey: memberKeys.list(accountId, params),
    queryFn: () => api.get<PaginatedResponse<Member>>(`/v1/accounts/${accountId}/members`, params),
  })
}

export function globalMemberListOptions(params: PaginationInput) {
  return queryOptions({
    queryKey: memberKeys.globalList(params),
    queryFn: () => api.get<PaginatedResponse<MemberWithAccount>>('/v1/members', params),
  })
}

export const memberMutations = {
  create: (accountId: string, data: Record<string, unknown>) =>
    api.post<Member>(`/v1/accounts/${accountId}/members`, data),

  update: (id: string, data: Record<string, unknown>) =>
    api.patch<Member>(`/v1/members/${id}`, data),

  delete: (id: string) =>
    api.del<Member>(`/v1/members/${id}`),

  move: (id: string, accountId?: string) =>
    api.post<Member>(`/v1/members/${id}/move`, accountId ? { accountId } : {}),
}

export type { MemberWithAccount }
