import qs from "qs"
import useSWR from "swr"
import { fetchApi } from "./base"

export interface IProgram {
  id: string
  subject: string
  content: string
  tag: string[]
  status: string
  updated_at: Date
  created_at: Date
}

export interface ProgramFormValue extends Omit<IProgram, "id" | "created_at" | "updated_at" | "status"> {}

interface ProgramParams {
  id?: string
  q?: string
  tag?: string
  page?: number
  limit?: number
}

export interface ProgramResponse {
  message: string
  data: any
}

export interface ProgramsResponse {
  message: string
  data: IProgram[]
  total: number
  page: number
  totalPage: number
  pageSize: number
}

export const usePrograms = (params: ProgramParams = {}) => {
  const url = `api/program?${qs.stringify(params)}`
  return useSWR<ProgramsResponse>(url)
}

export const useProgram = (params: ProgramParams = {}) => {
  const id = params.id ? (params.id as string) : ""
  const url = `api/program/${id}`
  return useSWR<ProgramResponse>(url)
}

export const create = (value: ProgramFormValue) => {
  return fetchApi.post(`api/program`, { body: JSON.stringify(value) })
}

export const update = (id: string, value: ProgramFormValue) => {
  return fetchApi.put(`api/program/${id}`, { body: JSON.stringify(value) })
}
