import type { User } from './dto/user'
import { extractItems } from '~/utils/api'

export const listUsers = async () => {
  const api = useApi()
  const data = await api.get<User[] | { 'hydra:member'?: User[] }>(
    '/users',
    {},
    { toast: false }
  )
  return extractItems<User>(data)
}

export const createUser = async (payload: {
  username: string
  plainPassword: string
  roles: string[]
  employeeId?: number | null
  isLocked?: boolean
  hasLeaveRecapAccess?: boolean
}) => {
  const api = useApi()
  return api.post<User>(
    '/users',
    {
      username: payload.username,
      plainPassword: payload.plainPassword,
      roles: payload.roles,
      employee: payload.employeeId ? `/api/employees/${payload.employeeId}` : null,
      isLocked: payload.isLocked ?? false,
      hasLeaveRecapAccess: payload.hasLeaveRecapAccess ?? false
    },
    {
      toastSuccessKey: 'success.user.create',
      toastErrorKey: 'errors.user.create'
    }
  )
}

export const updateUser = async (id: number, payload: {
  username: string
  plainPassword?: string
  roles: string[]
  employeeId?: number | null
  isLocked?: boolean
  hasLeaveRecapAccess?: boolean
}) => {
  const api = useApi()
  const body: Record<string, unknown> = {
    username: payload.username,
    roles: payload.roles,
    employee: payload.employeeId ? `/api/employees/${payload.employeeId}` : null,
    isLocked: payload.isLocked ?? false,
    hasLeaveRecapAccess: payload.hasLeaveRecapAccess ?? false
  }

  if (payload.plainPassword) {
    body.plainPassword = payload.plainPassword
  }

  return api.patch<User>(`/users/${id}`, body, {
    toastSuccessKey: 'success.user.update',
    toastErrorKey: 'errors.user.update'
  })
}
