import { useQuery } from '@tanstack/react-query'
import { z } from 'zod'
import { api } from '../client'
import type { Pipeline } from '../../types/api'

const pipelineSchema = z.object({
  id: z.number(),
  repoId: z.number(),
  ref: z.string(),
  status: z.enum(['pending', 'running', 'success', 'failure', 'cancelled']),
  createdAt: z.string(),
  updatedAt: z.string(),
})

const pipelinesSchema = z.array(pipelineSchema)

export function usePipelines(owner: string, repo: string) {
  return useQuery({
    queryKey: ['repos', owner, repo, 'pipelines'],
    queryFn: () =>
      api.get<Pipeline[]>(`/api/v1/repos/${owner}/${repo}/pipelines`, pipelinesSchema),
    enabled: Boolean(owner && repo),
    refetchInterval: 5000, // poll while pipelines may be running
  })
}

export function usePipeline(owner: string, repo: string, runId: number) {
  return useQuery({
    queryKey: ['repos', owner, repo, 'pipelines', runId],
    queryFn: () =>
      api.get<Pipeline>(
        `/api/v1/repos/${owner}/${repo}/pipelines/${runId}`,
        pipelineSchema,
      ),
    enabled: Boolean(owner && repo && runId),
  })
}
