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

const issueSchema = z.object({
  id: z.number(),
  repoId: z.number(),
  authorId: z.number(),
  authorName: z.string(),
  number: z.number(),
  title: z.string(),
  body: z.string(),
  state: z.enum(['open', 'closed']),
  createdAt: z.string(),
  updatedAt: z.string(),
})

const issuesSchema = z.array(issueSchema)

export function useIssues(owner: string, repo: string, state: IssueState = 'open') {
  return useQuery({
    queryKey: ['repos', owner, repo, 'issues', state],
    queryFn: () =>
      api.get<Issue[]>(`/api/v1/repos/${owner}/${repo}/issues?state=${state}`, issuesSchema),
    enabled: Boolean(owner && repo),
  })
}

export function useCreateIssue(owner: string, repo: string) {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: (data: { title: string; body?: string }) =>
      api.post<Issue>(`/api/v1/repos/${owner}/${repo}/issues`, issueSchema, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['repos', owner, repo, 'issues'] })
    },
  })
}

export function useCloseIssue(owner: string, repo: string) {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: (issueNum: number) =>
      api.post<Issue>(
        `/api/v1/repos/${owner}/${repo}/issues/${issueNum}/close`,
        issueSchema,
        {},
      ),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['repos', owner, repo, 'issues'] })
    },
  })
}

export function useReopenIssue(owner: string, repo: string) {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: (issueNum: number) =>
      api.post<Issue>(
        `/api/v1/repos/${owner}/${repo}/issues/${issueNum}/reopen`,
        issueSchema,
        {},
      ),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['repos', owner, repo, 'issues'] })
    },
  })
}
