import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { z } from 'zod'
import { api } from '../client'
import type { RepoMember } from '../../types/api'

const memberSchema = z.object({
  userId: z.number(),
  username: z.string(),
  avatarUrl: z.string().default(''),
  permission: z.enum(['read', 'write', 'admin']),
  isOwner: z.boolean(),
  addedAt: z.string().default(''),
})

const membersSchema = z.array(memberSchema)

export function useRepoMembers(owner: string, repo: string) {
  return useQuery({
    queryKey: ['repos', owner, repo, 'members'],
    queryFn: () =>
      api.get<RepoMember[]>(`/api/v1/repos/${owner}/${repo}/members`, membersSchema),
    enabled: Boolean(owner && repo),
  })
}

export function useAddMember(owner: string, repo: string) {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: (data: { username: string; permission: string }) =>
      api.post<RepoMember>(
        `/api/v1/repos/${owner}/${repo}/members`,
        memberSchema,
        data,
      ),
    onSuccess: () =>
      queryClient.invalidateQueries({ queryKey: ['repos', owner, repo, 'members'] }),
  })
}

export function useUpdateMember(owner: string, repo: string) {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: ({ username, permission }: { username: string; permission: string }) =>
      api.patch<RepoMember>(
        `/api/v1/repos/${owner}/${repo}/members/${username}`,
        memberSchema,
        { permission },
      ),
    onSuccess: () =>
      queryClient.invalidateQueries({ queryKey: ['repos', owner, repo, 'members'] }),
  })
}

export function useRemoveMember(owner: string, repo: string) {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: (username: string) =>
      api.delete(
        `/api/v1/repos/${owner}/${repo}/members/${username}`,
        z.any(),
      ),
    onSuccess: () =>
      queryClient.invalidateQueries({ queryKey: ['repos', owner, repo, 'members'] }),
  })
}
