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

const lfsSettingsSchema = z.object({
  enabled: z.boolean(),
  lockingEnabled: z.boolean(),
  maxFileSizeMB: z.number(),
})

export type LFSSettings = z.infer<typeof lfsSettingsSchema>

export function useLFSSettings(owner: string, repo: string) {
  return useQuery({
    queryKey: ['repos', owner, repo, 'lfs-settings'],
    queryFn: () =>
      api.get<LFSSettings>(`/api/v1/repos/${owner}/${repo}/lfs-settings`, lfsSettingsSchema),
    enabled: Boolean(owner && repo),
  })
}

export function useUpdateLFSSettings(owner: string, repo: string) {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: (body: Partial<LFSSettings>) =>
      api.put<LFSSettings>(`/api/v1/repos/${owner}/${repo}/lfs-settings`, lfsSettingsSchema, body),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['repos', owner, repo, 'lfs-settings'] })
    },
  })
}
