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

const secretSchema = z.object({
  id: z.number(),
  name: z.string(),
  createdAt: z.string(),
  updatedAt: z.string(),
})

const secretsSchema = z.array(secretSchema)

// ── Repo secrets ──────────────────────────────────────────────────────────────

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

export function useUpsertRepoSecret(owner: string, repo: string) {
  const qc = useQueryClient()
  return useMutation({
    mutationFn: (body: { name: string; value: string }) =>
      api.post<SecretListItem>(`/api/v1/repos/${owner}/${repo}/secrets`, secretSchema, body),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['repos', owner, repo, 'secrets'] }),
  })
}

export function useDeleteRepoSecret(owner: string, repo: string) {
  const qc = useQueryClient()
  return useMutation({
    mutationFn: (name: string) =>
      api.delete<void>(
        `/api/v1/repos/${owner}/${repo}/secrets/${encodeURIComponent(name)}`,
        z.unknown() as z.ZodType<void>,
      ),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['repos', owner, repo, 'secrets'] }),
  })
}

// ── Environment secrets ───────────────────────────────────────────────────────

export function useEnvSecrets(owner: string, repo: string, envName: string) {
  return useQuery({
    queryKey: ['repos', owner, repo, 'environments', envName, 'secrets'],
    queryFn: () =>
      api.get<SecretListItem[]>(
        `/api/v1/repos/${owner}/${repo}/environments/${envName}/secrets`,
        secretsSchema,
      ),
    enabled: Boolean(owner && repo && envName),
  })
}

export function useUpsertEnvSecret(owner: string, repo: string, envName: string) {
  const qc = useQueryClient()
  return useMutation({
    mutationFn: (body: { name: string; value: string }) =>
      api.post<SecretListItem>(
        `/api/v1/repos/${owner}/${repo}/environments/${envName}/secrets`,
        secretSchema,
        body,
      ),
    onSuccess: () =>
      qc.invalidateQueries({ queryKey: ['repos', owner, repo, 'environments', envName, 'secrets'] }),
  })
}

export function useDeleteEnvSecret(owner: string, repo: string, envName: string) {
  const qc = useQueryClient()
  return useMutation({
    mutationFn: (name: string) =>
      api.delete<void>(
        `/api/v1/repos/${owner}/${repo}/environments/${envName}/secrets/${encodeURIComponent(name)}`,
        z.unknown() as z.ZodType<void>,
      ),
    onSuccess: () =>
      qc.invalidateQueries({ queryKey: ['repos', owner, repo, 'environments', envName, 'secrets'] }),
  })
}

// ── Workspace secrets ─────────────────────────────────────────────────────────

export function useWorkspaceSecrets(handle: string) {
  return useQuery({
    queryKey: ['workspaces', handle, 'secrets'],
    queryFn: () =>
      api.get<SecretListItem[]>(`/api/v1/workspaces/${handle}/secrets`, secretsSchema),
    enabled: Boolean(handle),
  })
}

export function useUpsertWorkspaceSecret(handle: string) {
  const qc = useQueryClient()
  return useMutation({
    mutationFn: (body: { name: string; value: string }) =>
      api.post<SecretListItem>(`/api/v1/workspaces/${handle}/secrets`, secretSchema, body),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['workspaces', handle, 'secrets'] }),
  })
}

export function useDeleteWorkspaceSecret(handle: string) {
  const qc = useQueryClient()
  return useMutation({
    mutationFn: (name: string) =>
      api.delete<void>(
        `/api/v1/workspaces/${handle}/secrets/${encodeURIComponent(name)}`,
        z.unknown() as z.ZodType<void>,
      ),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['workspaces', handle, 'secrets'] }),
  })
}
