import { useQuery } from '@tanstack/react-query'
import { z } from 'zod'
import { api } from '../client'

const exploreRepoSchema = z.object({
  id: z.number(),
  name: z.string(),
  description: z.string(),
  isPrivate: z.boolean(),
  defaultBranch: z.string(),
  createdAt: z.string(),
  updatedAt: z.string(),
  ownerId: z.number(),
  ownerUsername: z.string(),
  ownerAvatarUrl: z.string(),
})
const exploreReposSchema = z.array(exploreRepoSchema)
export type ExploreRepo = z.infer<typeof exploreRepoSchema>

const exploreUserSchema = z.object({
  id: z.number(),
  username: z.string(),
  avatarUrl: z.string(),
  createdAt: z.string(),
})
const exploreUsersSchema = z.array(exploreUserSchema)
export type ExploreUser = z.infer<typeof exploreUserSchema>

export function useExploreRepos(q: string, sort: string, offset: number) {
  const params = new URLSearchParams({ q, sort, limit: '20', offset: String(offset) })
  return useQuery({
    queryKey: ['explore', 'repos', q, sort, offset],
    queryFn: () =>
      api.get<ExploreRepo[]>(`/api/v1/explore/repos?${params}`, exploreReposSchema),
    placeholderData: prev => prev,
  })
}

export function useExploreUsers(q: string, offset: number) {
  const params = new URLSearchParams({ q, limit: '20', offset: String(offset) })
  return useQuery({
    queryKey: ['explore', 'users', q, offset],
    queryFn: () =>
      api.get<ExploreUser[]>(`/api/v1/explore/users?${params}`, exploreUsersSchema),
    placeholderData: prev => prev,
  })
}
