import { useQuery } from '@tanstack/vue-query'
import type { components } from './generated/schema'
import { apiClient } from './client'
import {
  throwApiProblem,
  type EntityRefDto,
  type EntityType,
} from './contracts'
import { queryKeys } from './queryClient'

type GeneratedActivityItemDto = components['schemas']['ActivityItemDto']
type GeneratedActivityPageDto = components['schemas']['ActivityPageDto']
type ActivityItemWireDto = GeneratedActivityItemDto & {
  entity?: components['schemas']['EntityRefDto'] | null
}

export type ActivityItemDto = GeneratedActivityItemDto & {
  entity: EntityRefDto | null
}

export type ActivityPageDto = Omit<GeneratedActivityPageDto, 'items'> & {
  items: ActivityItemDto[]
}

export async function fetchActivity(
  pageSize = 200,
  signal?: AbortSignal,
): Promise<ActivityPageDto> {
  const boundedPageSize = Math.min(Math.max(pageSize, 1), 200)
  const { data, error, response } = await apiClient.GET('/api/v1/activity', {
    params: {
      query: {
        page: 1,
        pageSize: boundedPageSize,
        sort: 'newest',
      },
    },
    signal,
  })
  if (!response.ok || error || !data) {
    await throwApiProblem(response, 'Nexus-Aktivität konnte nicht geladen werden')
  }
  const page = data as GeneratedActivityPageDto & { items: ActivityItemWireDto[] }
  return {
    ...page,
    items: page.items.map(item => ({
      ...item,
      entity: item.entity
        ? {
            ...item.entity,
            type: item.entity.type as EntityType,
          }
        : null,
    })),
  }
}

export function useActivity(pageSize = 200) {
  return useQuery({
    queryKey: queryKeys.activity(pageSize),
    queryFn: ({ signal }) => fetchActivity(pageSize, signal),
  })
}
