import {removeById} from '@crumbs/core/collections'
import type {TrailInvite} from '@crumbs/core/schemas'

import {createSlotStore, slotHooks} from '@/lib/async-slot'
import {unwrap} from '@/lib/errors'
import {rpc} from '@/lib/rpc'
import {refreshTrails} from '@/stores/trails'

export type {TrailInvite}

const useTrailInvitesStore = createSlotStore<TrailInvite[]>(
  [],
  async () => {
    const {invites} = await unwrap(rpc.trails.invites.$get())
    return invites
  },
)

const removeInvite = (id: string) =>
  useTrailInvitesStore.setState((s) => ({
    data: removeById(s.data, id),
  }))

const accept = async (id: string) => {
  await unwrap(
    rpc.trails.invites[':inviteId'].accept.$post({
      param: {inviteId: id},
    }),
  )
  removeInvite(id)
  await refreshTrails()
}

const decline = async (id: string) => {
  await unwrap(
    rpc.trails.invites[':inviteId'].decline.$post({
      param: {inviteId: id},
    }),
  )
  removeInvite(id)
}

export const {
  useData: useTrailInvites,
  useRefresh: useRefreshTrailInvites,
} = slotHooks(useTrailInvitesStore)
export const usePendingInviteCount = () =>
  useTrailInvitesStore((s) => s.data.length)
export const useAcceptTrailInvite = () => accept
export const useDeclineTrailInvite = () => decline
