import {Meta} from '@storybook/addon-docs/blocks'

<Meta title='@dxtmisha/en/functional-basic/Classes/ApiResponse - API Request Emulation'/>

# ApiResponse Class

A manager class for intercepting, caching, and emulating API responses. It allows you to intercept outgoing API requests and return predefined mock data instead of triggering actual physical network traffic.

> `ApiResponse` is an **auxiliary class**, designed for API emulation and mocking. In most cases, it is recommended to register mock responses through the `response` parameter in the global `Api` configuration.

## Key Features

- **Request Interception** — matches outbound requests intelligently based on target route, HTTP method, and payload object.
- **Dynamic Capabilities** — supports static predefined fallback objects or executes dynamic callback logic capable of interpreting request query context.
- **Network Lag Simulation** — built-in system specifically tailored for simulating actual latency ping scenarios (randomized offset timers).
- **Developer Mode** — prints useful debug information in browser consoles showing which payload mapped directly to a specific fallback mock point.

## Initialization

To initialize the object, call the constructor `ApiResponse(requestDefault)`.

**Parameters:**
- `requestDefault: ApiDefault` — default request class used for configuration and storage.

```typescript
import { ApiResponse } from '@dxtmisha/functional-basic'

const apiResponse = new ApiResponse(myApiDefault)
```

## Methods

### Action

#### `emulator`

Core engine loop that validates request configurations and executes matched routing latency mock responses. This method only runs in DOM environments.

**Parameters:**
- `apiFetch: ApiFetch` — The properties of the request to emulate.

**Returns:** `Promise<T | undefined>` — The emulated response data.

#### `emulatorAsync`

Synchronous version of the emulator. It returns the mock response immediately without any delay or loading state. This method only runs in DOM environments.

**Parameters:**
- `apiFetch: ApiFetch` — The properties of the request to emulate.

**Returns:** `T | undefined` — The emulated response data.

### Check

- `get(path: string, method: ApiMethod, request?: ApiFetch['request'], devMode?: boolean): ApiResponseItem | undefined` — Synchronously checks for a matching cached mock request.
- `getList(): (ApiResponseItem & Record<string, any>)[]` — Returns a list of all registered emulator configurations.

### Configuration

- `add(response: ApiResponseItem | ApiResponseItem[]): this` — Adds mock response objects to the local registry.
- `setDevMode(devMode: boolean): this` — Toggles the development debug log mode.

## Types

#### `ApiResponseItem`
An object defining a mock response configuration.
- `path: string | RegExp` — The matching URL path or pattern.
- `method: ApiMethod` — The HTTP method (GET, POST, etc.).
- `response: any | ((request?: any) => any)` — The mock data or a function returning it.
- `request?: ApiFetch['request'] | '*any'` — Optional request payload to match against.
- `lag?: boolean` — Whether to simulate network latency.
- `disable?: any` — Condition to disable the mock (boolean or function).
- `isForGlobal?: boolean` — Mark as global mock (hidden from getList).

## Guide: API Emulation

The following rules and conditions define how the emulation system intercepts and mocks network requests:

- **Mock Registration** — responses added via `add()` take precedence and are checked before any real network call is initiated.
- **Matching Criteria** — a mock is triggered only if the path (string or RegExp), HTTP method, and request body all match the configuration.
- **Body Wildcards** — using `*any` as the request value allows the mock to match any payload, bypassing deep object comparison.
- **Dynamic Data** — the `response` property can be a function, allowing you to generate dynamic mock data based on the incoming request parameters.
- **Latency Simulation** — setting `lag: true` adds a random delay (0-2000ms) and triggers the common loading state (`d-response-loading` class on body).
- **Match Persistence** — by default, an emulator configuration matches only once unless `devMode` is enabled, preventing duplicate mock triggers for the same state.
