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

export type OpenRecord = Record<string, unknown> & { id: number }
export type OpenSearch = { total: number; list: OpenRecord[]; counts: Record<string, number> }

export const openApi = {
  async search(params: Record<string, unknown>) {
    const { data } = await client.get<ApiResponse<OpenSearch>>(`${apiPrefix()}/opens/search`, { params })
    return unwrap(data)
  },
  async get(id: number) {
    const { data } = await client.get<ApiResponse<OpenRecord>>(`${apiPrefix()}/opens/${id}`)
    return unwrap(data)
  },
  async create(payload: Record<string, unknown>) {
    const { data } = await client.post<ApiResponse>(`${apiPrefix()}/opens`, payload)
    return unwrap(data)
  },
  async save(id: number, payload: Record<string, unknown>) {
    const { data } = await client.put<ApiResponse>(`${apiPrefix()}/opens/${id}`, payload)
    return unwrap(data)
  },
  async remove(id: number) {
    const { data } = await client.delete<ApiResponse>(`${apiPrefix()}/opens/${id}`)
    return unwrap(data)
  },
  async serialLookup(serial: string, gubun = '휴대폰') {
    const { data } = await client.get<ApiResponse<Record<string, unknown>[]>>(`${apiPrefix()}/opens/serial-lookup`, { params: { serial, gubun } })
    return unwrap(data)
  },
}
