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

const prSchema = z.object({
  id: z.number(),
  repoId: z.number(),
  authorId: z.number(),
  title: z.string(),
  body: z.string(),
  sourceBranch: z.string(),
  targetBranch: z.string(),
  status: z.enum(['open', 'merged', 'closed']),
  createdAt: z.string(),
  updatedAt: z.string(),
})

const prsSchema = z.array(prSchema)

const mergeResponseSchema = z.object({ status: z.string() })

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

export function usePR(owner: string, repo: string, prId: number) {
  return useQuery({
    queryKey: ['repos', owner, repo, 'pulls', prId],
    queryFn: () =>
      api.get<PullRequest>(`/api/v1/repos/${owner}/${repo}/pulls/${prId}`, prSchema),
    enabled: Boolean(owner && repo && prId),
  })
}

export function useMergePR(owner: string, repo: string) {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: (prId: number) =>
      api.post(`/api/v1/repos/${owner}/${repo}/pulls/${prId}/merge`, mergeResponseSchema, {}),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['repos', owner, repo, 'pulls'] })
    },
  })
}
