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

type LoginData = {
  token: string
  role: string
  userid: string
  name: string
  groupId: string
  companyId: number | null
  staffPermission?: string
  menuFlags?: string | null
}

export async function login(userid: string, password: string): Promise<User & { token: string }> {
  const { data } = await client.post<ApiResponse<LoginData>>('/auth/login', { userid, password })
  const body = unwrap(data)
  return {
    token: body.token,
    role: body.role,
    userid: body.userid,
    name: body.name,
    groupId: body.groupId,
    companyId: body.companyId,
    staffPermission: body.staffPermission,
    menuFlags: body.menuFlags,
  }
}

export type MyMenusData = {
  staffPermission: string
  menus: string[]
}

export async function fetchMyMenus(): Promise<MyMenusData> {
  const { data } = await client.get<ApiResponse<MyMenusData>>(`${apiPrefix()}/homes/my-menus`)
  return unwrap(data)
}

export async function me(): Promise<User> {
  const { data } = await client.get<ApiResponse<User>>('/auth/me')
  return unwrap(data)
}
