import useSWR from 'swr'
import { api } from '../api/client'

export interface Resource {
  id: string
  title: string
  description: string | null
  url: string
  icon: string | null
  category: string | null
  githubRepo: string | null
  downloadCdn: string | null
  downloadOriginal: string | null
  version: string | null
  background: boolean
  image: string | null
  order: number
  createdAt: string | Date
  updatedAt: string | Date
}

export interface Portal {
  id: string
  title: string
  url: string
  description: string | null
  icon: string | null
  background: boolean
  order: number
  createdAt: string | Date
  updatedAt: string | Date
}

export interface Comment {
  id: string
  content: string
  userId: string
  postId: string
  createdAt: string | Date
  updatedAt: string | Date
  user?: {
    name: string | null
    image?: string | null
  }
}

export interface Post {
  id: string
  title: string
  content: string
  userId: string
  createdAt: string | Date
  updatedAt: string | Date
  user?: {
    name: string | null
    image?: string | null
  }
  comments?: Comment[]
}

export function useResources() {
  const { data, error, isLoading, mutate } = useSWR('/resources', async () => {
    const { data, error } = await api.resources.get()
    if (error) throw error
    return data
  })

  return {
    resources: data,
    isLoading,
    isError: error,
    mutate,
  }
}

export function usePortals() {
  const { data, error, isLoading, mutate } = useSWR('/portals', async () => {
    const { data, error } = await api.portals.get()
    if (error) throw error
    return data
  })

  return {
    portals: data,
    isLoading,
    isError: error,
    mutate,
  }
}

export function usePosts() {
  const { data, error, isLoading, mutate } = useSWR('/posts', async () => {
    const { data, error } = await api.posts.get()
    if (error) throw error
    return data
  })

  return {
    posts: data,
    isLoading,
    isError: error,
    mutate,
  }
}

export function usePost(id: string) {
  const { data, error, isLoading, mutate } = useSWR(
    id ? `/posts/${id}` : null,
    async () => {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      const { data, error } = await (api.posts as any)[id].get()
      if (error) throw error
      return data
    },
  )

  return {
    post: data,
    isLoading,
    isError: error,
    mutate,
  }
}
