import { adminApi } from './client'
import { unwrapItem } from './helpers'
import { normalizeAuthUser } from './normalizers'
import type { ApiItemResponse } from './types'

type LoginPayload = {
  email: string
  password: string
}

type LoginResponse = {
  token: string
  user: unknown
}

export async function login(payload: LoginPayload) {
  const response = await adminApi.post<ApiItemResponse<LoginResponse>>(
    '/login',
    payload
  )

  const data = unwrapItem(response) as Record<string, unknown> & { token: string; user: unknown }
  return {
    token: data.token,
    user: normalizeAuthUser(data.user),
  }
}

export async function fetchMe() {
  const response = await adminApi.get<ApiItemResponse<unknown>>('/me')
  return normalizeAuthUser(response.data)
}

export async function logout() {
  await adminApi.post('/logout')
}
