import client, { apiPrefix, unwrap, type ApiResponse } from './client'
import type { Entity } from '../types'

export type PageResult<T = Entity> = { total: number; list: T[] }

export const resourceApi = {
  async list(path: string, params: Record<string, unknown> = {}) {
    const { data } = await client.get<ApiResponse<PageResult> | ApiResponse<Record<string, unknown>>>(
      `${apiPrefix()}/${path}`,
      { params },
    )
    const body = unwrap(data) as PageResult | Record<string, unknown>
    if (body && typeof body === 'object' && 'list' in body) {
      const page = body as PageResult
      return { items: page.list ?? [], total: Number(page.total ?? 0) }
    }
    // dashboard / summary style
    return { items: [body as Entity], total: 1, raw: body }
  },

  async get(path: string, params: Record<string, unknown> = {}) {
    const { data } = await client.get<ApiResponse>(`${apiPrefix()}/${path}`, { params })
    return unwrap(data)
  },

  async create(path: string, payload: Record<string, unknown>) {
    const { data } = await client.post<ApiResponse<Entity>>(`${apiPrefix()}/${path}`, payload)
    return unwrap(data)
  },

  async update(path: string, id: number | string, payload: Record<string, unknown>) {
    const { data } = await client.put<ApiResponse<Entity>>(`${apiPrefix()}/${path}/${id}`, payload)
    return unwrap(data)
  },

  async put(path: string, payload: Record<string, unknown>, params?: Record<string, unknown>) {
    const { data } = await client.put<ApiResponse>(`${apiPrefix()}/${path}`, payload, { params })
    return unwrap(data)
  },

  async remove(path: string, id: number) {
    const { data } = await client.delete<ApiResponse>(`${apiPrefix()}/${path}/${id}`)
    return unwrap(data)
  },
}
