import { apiRequest } from "@/shared/api/request";
import { API_ENDPOINTS, API_OPERATIONS, apiEndpointPath } from "@/shared/api/generated/endpoints";
import type { EntityId, PermissionDto, PermissionPayload, RoleDto, RolePayload } from "@/shared/api/types";

export function listRoles(): Promise<RoleDto[]> {
  return apiRequest<RoleDto[]>(apiEndpointPath(API_OPERATIONS.listRoles));
}

export function createRole(payload: RolePayload): Promise<RoleDto> {
  const endpoint = API_ENDPOINTS.createRole;
  return apiRequest<RoleDto, RolePayload>(apiEndpointPath(API_OPERATIONS.createRole), {
    body: payload,
    method: endpoint.method
  });
}

export function updateRole(id: EntityId, payload: RolePayload): Promise<RoleDto> {
  const endpoint = API_ENDPOINTS.updateRole;
  return apiRequest<RoleDto, RolePayload>(apiEndpointPath(API_OPERATIONS.updateRole, { id }), {
    body: payload,
    method: endpoint.method
  });
}

export function deleteRole(id: EntityId): Promise<unknown> {
  const endpoint = API_ENDPOINTS.deleteRole;
  return apiRequest(apiEndpointPath(API_OPERATIONS.deleteRole, { id }), { method: endpoint.method });
}

export function replaceRolePermissions(id: EntityId, permissionIds: number[]): Promise<unknown> {
  const endpoint = API_ENDPOINTS.replaceRolePermissions;
  return apiRequest<unknown, { permissionIds: number[] }>(apiEndpointPath(API_OPERATIONS.replaceRolePermissions, { id }), {
    body: { permissionIds },
    method: endpoint.method
  });
}

export function listPermissions(): Promise<PermissionDto[]> {
  return apiRequest<PermissionDto[]>(apiEndpointPath(API_OPERATIONS.listPermissions));
}

export function createPermission(payload: PermissionPayload): Promise<PermissionDto> {
  const endpoint = API_ENDPOINTS.createPermission;
  return apiRequest<PermissionDto, PermissionPayload>(apiEndpointPath(API_OPERATIONS.createPermission), {
    body: payload,
    method: endpoint.method
  });
}

export function updatePermission(id: EntityId, payload: PermissionPayload): Promise<PermissionDto> {
  const endpoint = API_ENDPOINTS.updatePermission;
  return apiRequest<PermissionDto, PermissionPayload>(apiEndpointPath(API_OPERATIONS.updatePermission, { id }), {
    body: payload,
    method: endpoint.method
  });
}

export function deletePermission(id: EntityId): Promise<unknown> {
  const endpoint = API_ENDPOINTS.deletePermission;
  return apiRequest(apiEndpointPath(API_OPERATIONS.deletePermission, { id }), { method: endpoint.method });
}

export function syncPermissions(): Promise<PermissionDto[]> {
  const endpoint = API_ENDPOINTS.syncPermissions;
  return apiRequest<PermissionDto[], Record<string, never>>(apiEndpointPath(API_OPERATIONS.syncPermissions), {
    body: {},
    method: endpoint.method
  });
}
