# @plyaz/api

> ⚡ Smart, type-safe API client for the Plyaz ecosystem with zero-configuration intelligence

[![Version](https://img.shields.io/badge/version-1.0.2-blue.svg)](https://github.com/Plyaz-Official/api)
[![TypeScript](https://img.shields.io/badge/TypeScript-5.7-blue.svg)](https://www.typescriptlang.org/)
[![License](https://img.shields.io/badge/license-ISC-green.svg)](LICENSE)

**@plyaz/api** is the unified API client for seamless backend communication across the Plyaz platform. Built on [fetchff](https://www.npmjs.com/package/fetchff), it provides intelligent defaults, automatic optimizations, and full TypeScript support for Web3, authentication, and tokenized experiences.

---

## ✨ Why @plyaz/api?

### Zero-Configuration Smart Features

The API client works intelligently out of the box:

| Feature | What It Does | Default Behavior | When to Override |
|---------|--------------|------------------|------------------|
| **Request Deduplication** | Prevents duplicate requests | 2-second window | Real-time data needs |
| **Automatic Retry** | Retries failed requests | 3 retries with exponential backoff | Critical operations |
| **Response Caching** | Caches successful responses | 10min cache, 2min stale | Static vs real-time data |
| **Network Adaptation** | Adjusts to connection quality | Automatic detection | Custom performance needs |
| **Smart Headers** | Sets appropriate headers | JSON content-type | File uploads, GraphQL |
| **Timeout Handling** | Prevents hanging requests | 30 seconds | Long-running operations |

### Pre-Configured Endpoints

All endpoints are pre-defined and fully typed. No configuration needed:

```typescript
const api = await createApiClient({ baseURL: 'https://api.example.com' });

// Pre-configured, fully typed methods ready to use!
const { data } = await api.getUsers();
const { data: campaign } = await api.getCampaign({ id: '123' });
```

---

## 📦 Installation

```bash
pnpm add @plyaz/api
```

**Requirements:**
- Node.js >= 22.4.0
- pnpm >= 8.0.0

---

## 🚀 Quick Start

### Simple REST API (2 lines)

```typescript
const api = await createApiClient({ baseURL: 'https://api.example.com' });
const { data } = await api.getUsers();
```

### Authenticated API

```typescript
const api = await createApiClient({
  baseURL: 'https://api.example.com',
  headers: async () => ({
    Authorization: `Bearer ${await getToken()}`
  })
});
```

### Mobile App (Network-aware)

```typescript
const api = await createApiClient({
  baseURL: 'https://api.example.com',
  performanceStrategy: 'mobile',
  networkAware: { enabled: true }
});
```

### Real-Time Dashboard

```typescript
const api = await createApiClient({
  baseURL: 'https://api.example.com',
  unifiedStrategy: 'realtime',
  revalidationStrategy: 'aggressive'
});
```

---

## 🎯 Complete Feature Set

### Core Request Features

| Feature | Type | Description | Default | Configuration |
|---------|------|-------------|---------|---------------|
| **🔒 Type Safety** | Auto | Full TypeScript support with intelligent type inference | Enabled | N/A - Always active |
| **⚡ Smart Defaults** | Auto | Zero-config setup, works perfectly out of the box | Enabled | Override via config |
| **📋 Pre-Configured Endpoints** | Auto | Typed endpoint methods ready to use | All endpoints | Override with `endpoints` |
| **🔁 Request Deduplication** | Auto | Prevents duplicate requests within time window | 2-second window | `dedupeTime: number` |
| **⏱️ Timeout Handling** | Auto | Prevents hanging requests | 30 seconds | `timeout: number` |
| **🚦 Request Cancellation** | Manual | AbortController support | Available | `cancellable: true` |
| **🔗 Request Chaining** | Manual | Chain multiple requests efficiently | Available | Standard usage |
| **🔌 Interceptors** | Manual | Request/response/error interceptors | None | `onRequest`, `onResponse`, `onError` |

### Retry & Resilience

| Feature | Type | Description | Default | Configuration |
|---------|------|-------------|---------|---------------|
| **🔄 Retry Logic** | Auto | Exponential backoff for failed requests | 3 retries, 1s delay, 1.5x backoff | `retry: { retries, delay, backoff }` |
| **🎯 Retry Strategies** | Manual | Customizable retry strategies (none, minimal, standard, etc.) | `standard` | `retryStrategy: string` |
| **🔍 Retry Conditions** | Manual | Conditional retry based on status codes, errors | Standard HTTP errors | `retryOn: number[]` |
| **⚠️ Status Code Limits** | Manual | Define retry behavior per status code | 408, 429, 500, 502, 503, 504 | Custom limits |

### Caching & Revalidation

| Feature | Type | Description | Default | Configuration |
|---------|------|-------------|---------|---------------|
| **💾 Response Caching** | Auto | Multi-level caching (memory, session, persistent) | 10min cache, 2min stale | `cacheTime`, `staleTime` |
| **📦 Cache Strategies** | Manual | 6 strategies (none, minimal, standard, moderate, aggressive, offline) | `standard` | `cacheStrategy: string` |
| **🔑 Cache Key Patterns** | Manual | Custom cache key generation patterns | Standard pattern | `buildCacheKey()` |
| **🗑️ Cache Invalidation** | Manual | Invalidation scenarios and utilities | Available | `mutate()`, `deleteCache()` |
| **♻️ Revalidation** | Auto | 9 strategies (focus, reconnect, interval, etc.) | On focus/reconnect | `revalidationStrategy: string` |
| **🔄 Manual Revalidation** | Manual | Programmatic cache revalidation | Available | `revalidate()`, `revalidateAll()` |

### Network & Performance

| Feature | Type | Description | Default | Configuration |
|---------|------|-------------|---------|---------------|
| **🌐 Network Detection** | Auto | Detects connection quality and adapts | Enabled | `networkAware: { enabled }` |
| **📊 Network Quality** | Auto | Monitors network quality (excellent, good, slow, offline) | Automatic | Auto-detection |
| **🎯 Performance Strategies** | Manual | Optimized presets (mobile, realtime, static, etc.) | `standard` | `performanceStrategy: string` |
| **⚙️ Network Config Manager** | Auto | Manages network-optimized configurations | Enabled | Automatic management |
| **💻 Platform Detection** | Auto | Detects platform (browser, Node.js, Electron, etc.) | Automatic | Auto-detection |
| **📱 Device Detection** | Auto | Detects device type and capabilities | Automatic | Auto-detection |
| **🔍 Client Hints** | Auto | Enhanced client hints for network optimization | Enabled | Automatic detection |
| **⚡ Adaptive Performance** | Auto | Adapts behavior based on device/network | Enabled | Automatic adaptation |
| **📈 Performance Monitoring** | Auto | Tracks request timing and performance metrics | Enabled | Automatic tracking |
| **💤 Data Saver Mode** | Auto | Detects and respects data saver preferences | Enabled | Automatic detection |

### Headers & Regional

| Feature | Type | Description | Default | Configuration |
|---------|------|-------------|---------|---------------|
| **📝 Header Management** | Auto | Smart header enrichment and presets | JSON content-type | `headers: {}` or `headers: () => {}` |
| **✨ Enriched Headers** | Auto | Automatic header enrichment with platform/network data | Enabled | `enrichedHeaders: boolean` |
| **🎨 Header Presets** | Manual | Pre-configured header sets (json, multipart, etc.) | Available | `headerPresets` |
| **🔐 Authentication** | Manual | Token management and auth interceptors | None | `onRequest` interceptor |
| **🌍 Regional Compliance** | Auto | GDPR, CCPA, APAC support | Enabled | `regionalConfig` |
| **🗺️ Regional Detection** | Auto | Auto-detect user region for compliance | Enabled | Automatic detection |
| **🎯 Regional Presets** | Manual | Region-specific configuration presets | Available | Regional presets |

### Configuration Management

| Feature | Type | Description | Default | Configuration |
|---------|------|-------------|---------|---------------|
| **📊 Config Levels** | Auto | 4-level hierarchy (global → client → request → temporary) | All levels active | Config hierarchy |
| **🔄 Config Merging** | Auto | Smart deep merging of configuration objects | Enabled | Automatic merging |
| **⚙️ Merge Strategies** | Manual | Custom merge strategies for config properties | Deep merge | Custom strategies |
| **🔀 Temporary Overrides** | Manual | Temporary config overrides with auto-reset | Available | `applyTemporaryOverride()` |
| **📋 Override Tracking** | Auto | Tracks all configuration overrides | Enabled | Automatic tracking |
| **🎯 Config Update Strategy** | Manual | 3 strategies (merge, replace, temporary) | Merge | `configOverride.strategy` |
| **🎨 Handler Strategy** | Manual | 4 strategies (merge, replace, prepend, append) | Merge | `configOverride.handlerStrategy` |
| **📍 Event Scopes Control** | Manual | Control which scopes receive events | All scopes | `configOverride.eventScopes` |
| **🧹 Auto-Clear Overrides** | Manual | Auto-clear temporary overrides after request | Disabled | `configOverride.clearOnComplete` |
| **⚡ Priority Mode** | Manual | Only highest priority handler runs | Disabled | `configOverride.priority` |
| **💾 Preserved Config** | Auto | Preserves original config for restoration | Enabled | Automatic preservation |
| **🔍 Config Debugger** | Manual | Detect configuration conflicts | Available | `useApiConfigConflicts()` |
| **⚠️ Conflict Detection** | Manual | Detects conflicting configurations | Available | `checkConflicts()` |
| **🌐 Global Config API** | Manual | Set/get/update global configuration | Available | Global config methods |
| **📝 Config Validation** | Auto | Validates configuration at runtime | Enabled | Automatic validation |

### Tracking & Telemetry

| Feature | Type | Description | Default | Configuration |
|---------|------|-------------|---------|---------------|
| **🎛️ Master Tracking Switch** | Manual | Enable/disable all tracking features | Enabled | `tracking.enabled` |
| **📊 Operation Tracking** | Manual | Track operations for debugging (debugger queue) | Enabled | `tracking.operations` |
| **📡 Event Emission Control** | Manual | Control whether events are emitted/processed | Enabled | `tracking.events` |
| **⚙️ Queue Strategy** | Manual | 4 strategies (immediate, batch, throttle, debounce) | Batch | `tracking.queueStrategy` |
| **📤 Event Strategy** | Manual | Event processing (immediate, queued) | Immediate | `tracking.eventStrategy` |
| **⚡ Performance Mode** | Manual | 3 modes (full, minimal, off) | Full | `tracking.performanceMode` |
| **📜 History Size Limit** | Manual | Max operations to keep in history | 1000 | `tracking.historySize` |
| **⚠️ Max Conflicts Tracking** | Manual | Max conflicts to track | 100 | `tracking.maxConflicts` |
| **🚫 Skip History** | Manual | Skip adding entries to history for this request | Disabled | `tracking.skipHistory` |
| **📈 Telemetry Collection** | Manual | Analytics/monitoring data collection | Disabled | `tracking.telemetry` |
| **🎯 Context-Aware Tracking** | Auto | Different defaults for test vs production | Auto-detected | Environment-based |

### Events & Monitoring

| Feature | Type | Description | Default | Configuration |
|---------|------|-------------|---------|---------------|
| **📊 Event System** | Auto | 80+ events across 8 namespaces | Enabled | `on()`, `off()`, `emit()` |
| **🎯 Event Namespaces** | Auto | 8 namespaces (headers, network, errors, debug, config, perf, client, cache) | All active | Namespace filtering |
| **📍 Event Scopes** | Auto | 4 scopes (GLOBAL → CONFIG → CLIENT → REQUEST) | All scopes | Scope-based handlers |
| **🔄 Handler Strategies** | Manual | 4 strategies (merge, replace, prepend, append) | Merge | `handlerStrategy` config |
| **⚡ Event Priorities** | Auto | Priority-based event execution | By scope priority | Automatic prioritization |
| **⚙️ Queue System** | Auto | Priority-based async operation processing | Enabled | Automatic batching |
| **📦 Batch Processing** | Auto | Batches events for efficient processing | 10ms window | Batch config |
| **🔔 Network Events** | Auto | Network state change events | Enabled | Event subscriptions |
| **📦 PubSub System** | Manual | Real-time subscriptions and updates | Available | Event subscriptions |
| **🎣 React Hooks** | Manual | 4 monitoring hooks (monitor, debug, config, network) | Available | `useApiMonitor()`, etc. |
| **📈 Event Statistics** | Manual | Get stats on event emissions and handlers | Available | `getEventStats()` |
| **🎯 Scoped Handlers** | Manual | Register handlers at specific scopes | Available | Scope parameter |
| **⏱️ Once Handlers** | Manual | Handlers that execute only once | Available | `once()` method |
| **🚫 Handler Removal** | Manual | Unregister event handlers | Available | `off()` method |

### Debugging & Diagnostics

| Feature | Type | Description | Default | Configuration |
|---------|------|-------------|---------|---------------|
| **🐛 Debug Tools** | Manual | Built-in debugging and analysis tools | Available | `getDebugInfo()` |
| **📋 Debug Reporting** | Manual | Generate comprehensive debug reports | Available | `generateReport()` |
| **📊 Operation Tracking** | Auto | Tracks all API operations for debugging | Enabled | Automatic tracking |
| **📜 History Tracking** | Auto | Maintains request/response history (LRU) | Enabled | Automatic tracking |
| **🔍 Issue Analysis** | Manual | Analyzes issues and provides recommendations | Available | Debug factories |
| **📊 Performance Analysis** | Manual | Analyzes performance bottlenecks | Available | Performance factory |

### Strategies & Patterns

| Feature | Type | Description | Default | Configuration |
|---------|------|-------------|---------|---------------|
| **🎯 Unified Strategies** | Manual | Combined strategy presets (realtime, mobile, etc.) | Available | `unifiedStrategy: string` |
| **🔄 Polling Strategies** | Manual | Progressive, conditional, visibility-aware polling | Available | Polling config |
| **♻️ Revalidation Strategies** | Manual | 9 revalidation patterns | On focus/reconnect | Strategy config |
| **⏰ Visibility-Aware** | Auto | Pauses operations when tab inactive | Enabled | Automatic behavior |
| **📈 Progressive Polling** | Manual | Gradually increasing poll intervals | Available | Progressive config |
| **🎯 Conditional Polling** | Manual | Poll based on conditions | Available | Conditional config |

### Error Handling

| Feature | Type | Description | Default | Configuration |
|---------|------|-------------|---------|---------------|
| **❌ Error Handling** | Auto | Standardized error handling with @plyaz/errors | 18 error types | `strategy: 'softFail' \| 'reject'` |
| **🎯 Error Strategies** | Manual | softFail, reject, silent, defaultResponse | `softFail` | `strategy` config |
| **🔔 Error Events** | Auto | Error event handlers (global, instance, once) | Enabled | Error event handlers |
| **📊 Error Categories** | Auto | Categorized errors (network, validation, auth, etc.) | Automatic | Built-in categories |

### Framework Integration

| Feature | Type | Description | Default | Configuration |
|---------|------|-------------|---------|---------------|
| **🚀 Next.js Middleware** | Manual | Next.js-specific integrations | Available | Framework middleware |
| **⚡ Express Middleware** | Manual | Express server-side integration | Available | Framework middleware |
| **🎯 NestJS Integration** | Manual | NestJS decorators and providers | Available | Framework middleware |
| **💻 SSR Support** | Auto | Server-side rendering safe operations | Enabled | SSR-safe configs |

### Utilities

| Feature | Type | Description | Default | Configuration |
|---------|------|-------------|---------|---------------|
| **🆔 ID Generation** | Auto | Request ID, Correlation ID generation | Enabled | Automatic generation |
| **⏱️ Time Utilities** | Manual | Time formatting, duration, delays | Available | Utility functions |
| **🔢 Math Utilities** | Manual | Percentage, clamping, averaging | Available | Utility functions |
| **📝 String Utilities** | Manual | String manipulation helpers | Available | Utility functions |
| **📦 Object Utilities** | Manual | Deep merge, clone, access | Available | Utility functions |
| **🔍 Type Guards** | Manual | Runtime type checking | Available | Utility functions |
| **✅ Validation** | Manual | Data validation utilities | Available | Utility functions |
| **⏰ Interval Manager** | Manual | Manage polling intervals | Available | Utility functions |
| **🎨 JSON Utilities** | Manual | Safe JSON parsing/stringifying | Available | Utility functions |

### Endpoints & Services

| Feature | Type | Description | Default | Configuration |
|---------|------|-------------|---------|---------------|
| **📋 Endpoint Builders** | Manual | Fluent API for building endpoint configurations | Available | Endpoint builder pattern |
| **🏗️ Endpoint Utilities** | Manual | Helper utilities for endpoint management | Available | Utility functions |
| **🎯 Services Layer** | Manual | Service functions with smart defaults per HTTP method | Available | `ServiceOptions` |
| **🔧 Campaign Services** | Manual | Complete CRUD operations for campaigns | Available | Service layer |
| **🎣 React Query Hooks** | Manual | Pre-built hooks (useCampaigns, useCreateCampaign, etc.) | Available | Hook factories |
| **📦 Endpoint Registry** | Auto | Maintains registry of all configured endpoints | Enabled | Automatic registration |
| **🔍 Endpoint Validation** | Auto | Validates endpoint configurations | Enabled | Automatic validation |

### Request Management

| Feature | Type | Description | Default | Configuration |
|---------|------|-------------|---------|---------------|
| **📝 Request Preparation** | Auto | Prepares requests with proper formatting | Enabled | Automatic preparation |
| **🚫 Abort Management** | Manual | Manage request cancellation via AbortController | Available | Abort utilities |
| **🔍 Request Routing** | Auto | Routes requests through proper pipeline | Enabled | Automatic routing |
| **📊 Request Utils** | Manual | Request preparation and management utilities | Available | Utility functions |
| **🆔 Request ID Tracking** | Auto | Automatic request ID generation and tracking | Enabled | Automatic generation |
| **🔗 Correlation ID** | Auto | Correlation ID for distributed tracing | Enabled | Automatic generation |

### Advanced Features

| Feature | Type | Description | Default | Configuration |
|---------|------|-------------|---------|---------------|
| **🔍 Request Fingerprinting** | Auto | Generates unique fingerprints for requests | Enabled | Automatic generation |
| **🔐 Header Sanitization** | Auto | Removes sensitive headers from logs | Enabled | Automatic sanitization |
| **🔍 Authentication Detection** | Auto | Detects auth type from headers | Enabled | Automatic detection |
| **📦 Multiple Clients** | Manual | Create and manage multiple client instances | Available | Standard usage |
| **🎯 Extended API Client** | Manual | ApiClientWithEvents with enhanced features | Available | Create extended client |
| **🔄 Client Factory Pattern** | Manual | Factory pattern for creating specialized clients | Available | Factory functions |
| **🎨 Color Utilities** | Manual | Console color utilities for logging | Available | Color helpers |
| **🌐 Environment Detection** | Auto | Detects runtime environment (browser/Node/Deno/Bun) | Enabled | Automatic detection |
| **📱 Push Notification Support** | Auto | Detects push notification capabilities | Enabled | Automatic detection |

### Legend
- **Auto**: Enabled by default, works automatically
- **Manual**: Available when needed, requires explicit usage
- **Total Features**: **110+** comprehensive features

---

## ⚙️ Service Configuration Reference

### ServiceOptions Interface

```typescript
interface ServiceOptions {
  /**
   * Optional API client instance override
   * Use this when you need a different client configuration
   * The client should have all endpoints from EndpointsList
   */
  apiClient?: ApiClientWithEvents<ClientEventManager, TEndpoints>;

  /**
   * Optional API configuration updates
   * By default applied with { strategy: 'temporary' } mode (affects only this request)
   * Can be overridden via updateConfigOptions
   */
  apiConfig?: Partial<ApiConfig>;

  /**
   * Optional update config options
   * Controls how apiConfig is applied to the client
   *
   * Defaults to: { strategy: 'temporary' }
   * - 'temporary': Only affects this request (highest priority)
   * - 'merge': Merges with client config (persists)
   * - 'replace': Replaces client config (persists)
   */
  updateConfigOptions?: UpdateConfigOptions;
}

/**
 * Config update options
 */
interface UpdateConfigOptions {
    strategy?: ConfigUpdateStrategy;
    priority?: number;
    namespace?: string;
    scope?: string;
    preserveFields?: (keyof ApiConfig)[];
}
```

### Available Unified Strategies

| Strategy | Cache | Retry | Use Case | Default For |
|----------|-------|-------|----------|-------------|
| **realtime** | None | Low | Live data, mutations | POST/PUT/DELETE |
| **interactive** | 2min stale, 10min cache | Medium | User-facing lists | GET (lists) |
| **background** | 10min stale, 30min cache | Medium | Background refreshes | GET (single items) |
| **mobile** | 5min stale, 15min cache | High | Mobile networks | - |
| **static** | 1hr stale, 24hr cache | Low | Rarely-changing data | - |

### Common Configuration Patterns

```typescript
// Pattern 1: Mobile-optimized
const serviceOptions: ServiceOptions = {
  apiConfig: {
    unifiedStrategy: 'mobile',
    networkAware: { enabled: true, adaptConfig: true },
    retry: { retries: 5, backoff: 2 }
  }
};

// Pattern 2: Real-time dashboard
const serviceOptions: ServiceOptions = {
  apiConfig: {
    unifiedStrategy: 'realtime',
    revalidationStrategy: 'aggressive',
    cacheStrategy: 'none'
  }
};

// Pattern 3: Static content
const serviceOptions: ServiceOptions = {
  apiConfig: {
    unifiedStrategy: 'static',
    cacheStrategy: 'aggressive',
    timeout: 10000
  }
};

// Pattern 4: Custom fine-tuned
const serviceOptions: ServiceOptions = {
  apiConfig: {
    timeout: 15000,
    retry: { retries: 3, delay: 2000, backoff: 2 },
    cacheStrategy: 'moderate',
    headers: {
      'X-Client-Version': '1.0.0',
      'X-Request-Priority': 'high'
    }
  }
};
```

---

## 📖 Usage Examples

### React Hooks

#### Data Fetching with Services

```typescript
import {
  useCampaigns,
  useCampaign,
  useCreateCampaign,
  useJoinCampaign,
} from '@plyaz/api/services/campaigns';
import { useQueryClient } from '@tanstack/react-query';
import type { ServiceOptions } from '@plyaz/api/services';

function CampaignList() {
  const queryClient = useQueryClient();

  // Basic query with smart defaults
  const { data, isLoading, error } = useCampaigns(
    ['campaigns', 'active'],
    { status: 'active' }
  );

  // Query with custom configuration
  const { data: searchResults } = useCampaigns(
    ['campaigns', 'search', searchTerm],
    { search: searchTerm },
    // ServiceOptions - API client config
    {
      apiConfig: {
        timeout: 5000,
        retry: { retries: 2 },
      }
    },
    // UseQueryOptions - React Query config
    {
      enabled: searchTerm.length > 2,
      staleTime: 30000,
      refetchOnWindowFocus: false,
    }
  );

  // Single item query with background caching
  const { data: campaign } = useCampaign(
    ['campaign', campaignId],
    { id: campaignId }
  );

  // Mutation with comprehensive handlers
  const { mutate: createCampaign, isPending } = useCreateCampaign(
    // ServiceOptions for API config
    {
      apiConfig: {
        timeout: 15000,
        headers: { 'X-Campaign-Source': 'web-app' },
      }
    },
    // Mutation options
    {
      onSuccess: (data) => {
        queryClient.invalidateQueries({ queryKey: ['campaigns'] });
        toast.success(`Campaign "${data.name}" created!`);
      },
      onError: (error) => {
        toast.error(`Failed to create: ${error.message}`);
      },
      onMutate: (variables) => {
        // Optimistic update
        const previousCampaigns = queryClient.getQueryData(['campaigns']);
        queryClient.setQueryData(['campaigns'], (old) => [...old, variables]);
        return { previousCampaigns };
      },
    }
  );

  // Multiple mutations with shared options
  const { mutate: joinCampaign } = useJoinCampaign(undefined, {
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['campaigns', campaignId] });
    }
  });

  if (isLoading) return <Spinner />;
  if (error) return <ErrorMessage error={error} />;

  return (
    <div>
      <CampaignGrid
        campaigns={data}
        onCreate={createCampaign}
        onJoin={joinCampaign}
        isPending={isPending}
      />
    </div>
  );
}
```

#### Hook Configuration Priority

```typescript
// The priority chain (lowest to highest):
// 1. Factory defaults (from createApiQuery/createApiMutation)
// 2. Hook-level defaults (when hook was created)
// 3. ServiceOptions parameter (API config)
// 4. UseQueryOptions parameter (React Query config)

// Example showing all levels:
const { data } = useCampaigns(
  ['campaigns'],
  { status: 'active' },           // Query parameters
  { apiConfig: { timeout: 10000 } }, // Level 3: Service options
  { staleTime: 60000 }            // Level 4: React Query options (highest)
);
```

#### Monitoring Hooks

```typescript
import { useApiMonitor, useApiNetworkQuality } from '@plyaz/api';

function Dashboard() {
  const { stats, isHealthy } = useApiMonitor(api);
  const { quality, isOnline } = useApiNetworkQuality();

  return <DashboardUI stats={stats} quality={quality} />;
}
```

### Service Functions

Service functions provide smart defaults based on HTTP method (GET/POST/PUT/DELETE) and allow granular configuration overrides.

#### Basic Usage

```typescript
import { fetchCampaigns, createCampaign } from '@plyaz/api/services/campaigns';

// Simple fetch with smart defaults (interactive caching for lists)
const response = await fetchCampaigns({ status: 'active' });

// Create with realtime strategy (no cache for mutations)
const created = await createCampaign({
  name: 'Summer Campaign',
  description: 'Q3 promotional campaign'
});
```

#### With ServiceOptions Configuration

```typescript
import type { ServiceOptions } from '@plyaz/api/services';

// Override API client configuration
const serviceOptions: ServiceOptions = {
  apiConfig: {
    timeout: 15000,                    // Custom timeout
    retry: { retries: 5, delay: 2000 }, // Aggressive retry
    headers: { 'X-Custom': 'value' },   // Additional headers
  }
};

const campaigns = await fetchCampaigns(
  { status: 'active', limit: 50 },
  serviceOptions
);

// Use different strategies
const realtimeData = await fetchCampaigns(
  { status: 'active' },
  {
    apiConfig: {
      unifiedStrategy: 'realtime',  // No cache, always fresh
      revalidationStrategy: 'none',
    }
  }
);

// Mobile-optimized configuration
const mobileData = await fetchCampaigns(
  { status: 'active' },
  {
    apiConfig: {
      unifiedStrategy: 'mobile',     // Mobile-friendly caching
      networkAware: { enabled: true }, // Adapt to connection
    }
  }
);
```

#### Error Handling Patterns

```typescript
import { isNotFoundError, isValidationError } from '@plyaz/errors';

// Pattern 1: Check response.error
const response = await fetchCampaigns({ status: 'active' });
if (response.error) {
  if (isNotFoundError(response.error)) {
    console.log('No campaigns found');
  }
  return;
}
console.log('Campaigns:', response.data);

// Pattern 2: Try-catch with throw
try {
  const { data, error } = await createCampaign(newCampaign);
  if (error) throw error;
  console.log('Created:', data);
} catch (err) {
  if (isValidationError(err)) {
    console.error('Invalid data:', err.message);
  }
}
```

#### Using Multiple Services

```typescript
import {
  fetchCampaign,
  fetchCampaignStats,
  fetchCampaignParticipants,
} from '@plyaz/api/services/campaigns';

// Fetch related data with consistent configuration
const serviceOpts: ServiceOptions = {
  apiConfig: { timeout: 10000 }
};

const [campaign, stats, participants] = await Promise.all([
  fetchCampaign({ id: '123' }, serviceOpts),
  fetchCampaignStats({ id: '123' }, serviceOpts),
  fetchCampaignParticipants({ id: '123' }, serviceOpts),
]);
```

### Custom Interceptors

```typescript
const api = await createApiClient({
  onRequest: (config) => {
    config.headers['X-Request-ID'] = generateRequestId();
    return config;
  },

  onResponse: (response) => {
    console.log(`Request completed in ${response.duration}ms`);
    return response;
  },

  onError: (error) => {
    if (error.status === 401) {
      redirectToLogin();
    }
    return error;
  }
});
```

### Error Handling

```typescript
import { isNotFoundError, isValidationError } from '@plyaz/errors';

const { data, error } = await api.getUser({ id: '123' });

if (error) {
  if (isNotFoundError(error)) {
    console.log('User not found');
  } else if (isValidationError(error)) {
    console.log('Invalid parameters');
  }
}
```

---

## 🏗️ Architecture

The @plyaz/api package orchestrates 21 internal modules to provide a seamless API experience:

```
Your App → createApiClient() → Smart Features → fetchff → Your API
              ↓
         [Automatic]
         • Retry Logic
         • Caching
         • Deduplication
         • Network Adaptation
         • Event System
         • Performance Tracking
```

**Want to understand how it works?** See the [Architecture Overview](./docs/USAGE.md#architecture-overview) and [Internal Architecture](./docs/INTERNAL.md).

---

## 📚 Documentation

- **[Usage Guide](./docs/USAGE.md)** - Complete usage documentation with examples
- **[API Reference](./docs/API-REFERENCE.md)** - Detailed API reference
- **[Internal Architecture](./docs/INTERNAL.md)** - Deep dive into internal systems
- **[Confluence Docs](https://plyaz.atlassian.net/wiki/spaces/SD/pages/950316/API+Package)** - Official documentation

---

## 🛠️ Development

### Setup

```bash
# Install dependencies
pnpm install

# Start development mode
pnpm dev
```

### Common Commands

```bash
pnpm dev              # Watch mode development
pnpm build            # Build the package
pnpm test             # Run tests
pnpm test:watch       # Watch mode testing
pnpm test:coverage    # Coverage report
pnpm lint             # Lint code
pnpm type:check       # Type checking
```

---

## 🔗 Integration with Plyaz Packages

| Package | Purpose | Usage |
|---------|---------|-------|
| **@plyaz/types** | Type definitions | API interfaces and types |
| **@plyaz/errors** | Error handling | Standardized error types |
| **@plyaz/config** | Configuration | API URLs and constants |

---

## 🎓 Learning Path

1. **Beginner**: Start with [Quick Start](#-quick-start) → Try the examples
2. **Intermediate**: Read [Usage Guide](./docs/USAGE.md) → Learn patterns
3. **Advanced**: Explore [API Reference](./docs/API-REFERENCE.md) → Master configuration
4. **Expert**: Study [Internal Architecture](./docs/INTERNAL.md) → Understand internals

---

## 🤝 Contributing

This package is part of the Plyaz platform. Please follow the [contribution guidelines](https://plyaz.atlassian.net/wiki/spaces/SD/pages/22544393) in the main repository.

---

## 📄 License

ISC © Plyaz

---

## 🔗 Links

- [Plyaz Platform Documentation](https://plyaz.atlassian.net/wiki/spaces/SD)
- [fetchff Documentation](https://www.npmjs.com/package/fetchff)
- [React Query Documentation](https://tanstack.com/query)
- [TypeScript Documentation](https://www.typescriptlang.org/)
