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

const commitEventSchema = z.object({
  type: z.literal('commit'),
  timestamp: z.string(),
  sha: z.string(),
  message: z.string(),
  author: z.string(),
})

const runEventSchema = z.object({
  type: z.literal('run'),
  timestamp: z.string(),
  runId: z.number(),
  triggerRef: z.string(),
  triggerSha: z.string(),
  triggeredBy: z.string(),
  runStatus: z.string(),
  startedAt: z.string().nullable().optional(),
  finishedAt: z.string().nullable().optional(),
})

const deploymentEventSchema = z.object({
  type: z.literal('deployment'),
  timestamp: z.string(),
  deploymentId: z.number(),
  envName: z.string(),
  deployStatus: z.string(),
  deployedSha: z.string(),
  deployRef: z.string(),
  triggeredBy: z.string(),
  description: z.string(),
  runLink: z.number().nullable().optional(),
})

const timelineEventSchema = z.discriminatedUnion('type', [
  commitEventSchema,
  runEventSchema,
  deploymentEventSchema,
])

const timelineSchema = z.array(timelineEventSchema)

export function useTimeline(owner: string, repo: string, limit = 60) {
  return useQuery({
    queryKey: ['repos', owner, repo, 'timeline', limit],
    queryFn: () =>
      api.get<TimelineEvent[]>(
        `/api/v1/repos/${owner}/${repo}/timeline?limit=${limit}`,
        timelineSchema as z.ZodType<TimelineEvent[]>,
      ),
    enabled: Boolean(owner && repo),
    refetchInterval: 30_000,
  })
}
