import http from './http'
import type {
  RbacRole, RbacUserView, RbacCatalog, SaveRolePayload, CreateUserPayload, UpdateUserPayload
} from '@/types/rbac'
import {
  mockRbacCatalog, mockRbacRoles, mockRbacSaveRole, mockRbacDeleteRole,
  mockRbacUsers, mockRbacCreateUser, mockRbacUpdateUser, mockRbacSetPassword, mockRbacDeleteUser
} from '@/mock/rbac'

const MOCK = import.meta.env.VITE_USE_MOCK === 'true'

export async function fetchCatalog(): Promise<RbacCatalog> {
  if (MOCK) return mockRbacCatalog()
  const { data } = await http.get<RbacCatalog>('/rbac/catalog')
  return data
}

export async function fetchRoles(): Promise<RbacRole[]> {
  if (MOCK) return mockRbacRoles()
  const { data } = await http.get<RbacRole[]>('/rbac/roles')
  return data
}

export async function saveRole(payload: SaveRolePayload): Promise<RbacRole> {
  if (MOCK) return mockRbacSaveRole(payload)
  if (payload.id) {
    const { data } = await http.put<RbacRole>(`/rbac/roles/${payload.id}`, payload)
    return data
  }
  const { data } = await http.post<RbacRole>('/rbac/roles', payload)
  return data
}

export async function deleteRole(id: string): Promise<void> {
  if (MOCK) return mockRbacDeleteRole(id)
  await http.delete(`/rbac/roles/${id}`)
}

export async function fetchUsers(): Promise<RbacUserView[]> {
  if (MOCK) return mockRbacUsers()
  const { data } = await http.get<RbacUserView[]>('/rbac/users')
  return data
}

export async function createUser(payload: CreateUserPayload): Promise<RbacUserView> {
  if (MOCK) return mockRbacCreateUser(payload)
  const { data } = await http.post<RbacUserView>('/rbac/users', payload)
  return data
}

export async function updateUser(id: string, payload: UpdateUserPayload): Promise<RbacUserView> {
  if (MOCK) return mockRbacUpdateUser(id, payload)
  const { data } = await http.put<RbacUserView>(`/rbac/users/${id}`, payload)
  return data
}

export async function setUserPassword(id: string, password: string): Promise<void> {
  if (MOCK) return mockRbacSetPassword(id, password)
  await http.put(`/rbac/users/${id}/password`, { password })
}

export async function deleteUser(id: string): Promise<void> {
  if (MOCK) return mockRbacDeleteUser(id)
  await http.delete(`/rbac/users/${id}`)
}
