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

export interface IUser {
  id: string
  name: string
  email: string
  social_id: string
  login_type: string
  picture: string
  tier: number
  rct: number
  rxt: number
  coin: number
  exp: number
  status: string
  accesstoken: string
  updated_at: Date
  created_at: Date
}

export interface IUserFormValue extends Omit<IUser, "id" | "created_at" | "updated_at"> {}

interface UserParams {
  accesstoken?: string
  name?: string
  email?: string
  page?: number
  limit?: number
}

export interface UsersResponse {
  message: string
  data: IUser[]
  page: {
    pageNumber: number
    pageSize: number
    totalPage: number
    totalNumber: number
  }
}

export interface ItemResponse {
  message: string
  data: IUser
}

export const useUsers = (params: UserParams = {}) => {
  return useSWR<UsersResponse>(`api/user?${qs.stringify(params)}`)
}

export const useUser = (id: string) => {
  return useSWR<ItemResponse>(`api/user/${id}`)
}

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

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