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

const statsSchema = z.object({
  repoCount: z.number(),
  openPRs: z.number(),
  reviewQueue: z.number(),
  openIssues: z.number(),
})

const dashPRSchema = z.object({
  id: z.number(),
  title: z.string(),
  sourceBranch: z.string(),
  targetBranch: z.string(),
  status: z.string(),
  createdAt: z.string(),
  updatedAt: z.string(),
  repoId: z.number(),
  repoName: z.string(),
  ownerName: z.string(),
  authorId: z.number(),
})

const dashIssueSchema = z.object({
  id: z.number(),
  number: z.number(),
  title: z.string(),
  state: z.string(),
  createdAt: z.string(),
  updatedAt: z.string(),
  repoId: z.number(),
  repoName: z.string(),
  ownerName: z.string(),
})

const dashRepoSchema = z.object({
  id: z.number(),
  name: z.string(),
  description: z.string(),
  isPrivate: z.boolean(),
  defaultBranch: z.string(),
  updatedAt: z.string(),
  ownerName: z.string(),
  avatarUrl: z.string(),
  openPrCount: z.number(),
  openIssueCount: z.number(),
})

const dashRunSchema = z.object({
  id: z.number(),
  repoId: z.number(),
  repoName: z.string(),
  ownerName: z.string(),
  triggerRef: z.string(),
  triggerSha: z.string(),
  triggeredBy: z.string(),
  status: z.string(),
  startedAt: z.string().nullable(),
  finishedAt: z.string().nullable(),
  createdAt: z.string(),
})

const dashboardSchema = z.object({
  stats: statsSchema,
  reviewQueue: z.array(dashPRSchema),
  myOpenPRs: z.array(dashPRSchema),
  myOpenIssues: z.array(dashIssueSchema),
  repos: z.array(dashRepoSchema),
  recentRuns: z.array(dashRunSchema).optional().default([]),
})

export type DashboardData = z.infer<typeof dashboardSchema>
export type DashPR = z.infer<typeof dashPRSchema>
export type DashIssue = z.infer<typeof dashIssueSchema>
export type DashRepo = z.infer<typeof dashRepoSchema>
export type DashRun = z.infer<typeof dashRunSchema>

export function useDashboard() {
  return useQuery({
    queryKey: ['dashboard'],
    queryFn: () => api.get<DashboardData>('/api/v1/dashboard', dashboardSchema),
    refetchInterval: 60_000,
    staleTime: 30_000,
  })
}
