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

const sshKeySchema = z.object({
  id: z.number(),
  userId: z.number(),
  title: z.string(),
  fingerprint: z.string(),
  publicKey: z.string(),
  createdAt: z.string(),
})

const sshKeysSchema = z.array(sshKeySchema)

export function useSSHKeys() {
  return useQuery({
    queryKey: ['user', 'keys'],
    queryFn: () => api.get<SSHKey[]>('/api/v1/user/keys', sshKeysSchema),
  })
}

export function useAddSSHKey() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: (data: { title: string; publicKey: string }) =>
      api.post<SSHKey>('/api/v1/user/keys', sshKeySchema, data),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ['user', 'keys'] }),
  })
}

export function useDeleteSSHKey() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: (keyId: number) =>
      api.delete(`/api/v1/user/keys/${keyId}`, z.any()),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ['user', 'keys'] }),
  })
}
