# API Integration Guide

This document explains how the front app integrates with the Strapi backend.

## Overview

The front app uses **axios** with custom interceptors to communicate with the Strapi API. All API requests are automatically configured with:
- Base URL from environment variables
- Authorization headers with Strapi API token
- Request/response logging in development mode
- Error handling

## Architecture

```
┌─────────────────┐
│   Components    │
│  (React/Next)   │
└────────┬────────┘
         │
         ▼
┌─────────────────┐
│    Services     │
│  (strapi.ts)    │
└────────┬────────┘
         │
         ▼
┌─────────────────┐
│  Axios Instance │
│  (axios.ts)     │
│  + Interceptors │
└────────┬────────┘
         │
         ▼
┌─────────────────┐
│  Strapi API     │
│  (Backend)      │
└─────────────────┘
```

## Files Structure

### `/src/lib/axios.ts`
Axios instance configuration with interceptors:
- **Request Interceptor**: Adds `Authorization: Bearer <token>` header to all requests
- **Response Interceptor**: Handles errors and logs responses in development

### `/src/services/strapi.ts`
Service layer for Strapi API calls:
- Type definitions for Strapi responses
- `getVideoUrl()` - Fetches the video-url single type data
- `getMediaUrl()` - Helper to get full URL for media files
- `getMediaFormatUrl()` - Helper to get specific format URLs (thumbnail, small, medium, large)

### `/src/components/VideoBackground.tsx`
Example component that fetches and displays video data from Strapi

## Usage Examples

### Basic API Call

```typescript
import axiosInstance from '@/lib/axios';

// GET request
const response = await axiosInstance.get('/api/endpoint');

// POST request
const response = await axiosInstance.post('/api/endpoint', {
  data: { ... }
});
```

### Using the Strapi Service

```typescript
import { getVideoUrl, getMediaUrl } from '@/services/strapi';

// Fetch video data
const videoData = await getVideoUrl();

// Get the full media URL
const url = getMediaUrl(videoData?.background);
```

### Creating New Services

To add more Strapi endpoints, follow this pattern in `src/services/strapi.ts`:

```typescript
// Define types
export interface MyContentType {
  id: number;
  title: string;
  // ... other fields
}

// Create service function
export async function getMyContent(): Promise<MyContentType | null> {
  try {
    const response = await axiosInstance.get<StrapiSingleTypeResponse<MyContentType>>(
      '/api/my-content',
      {
        params: {
          populate: '*',
        },
      }
    );
    return response.data.data;
  } catch (error) {
    console.error('Error fetching content:', error);
    return null;
  }
}
```

## Axios Interceptors

### Request Interceptor
Automatically adds to every request:
- `Authorization` header with Strapi token
- Development logging

```typescript
// Request log format
🚀 API Request: {
  method: 'GET',
  url: '/api/video-url',
  baseURL: 'http://localhost:1337',
  hasAuth: true
}
```

### Response Interceptor
Handles responses and errors:
- Success logging in development
- Error handling with specific status codes (401, 403, 404, 500)
- Detailed error messages

```typescript
// Response log format
✅ API Response: {
  status: 200,
  url: '/api/video-url',
  data: { ... }
}

// Error log format
❌ API Error Response: {
  status: 401,
  data: { error: 'Unauthorized' },
  url: '/api/video-url'
}
```

## Error Handling

The interceptors automatically handle common errors:

| Status Code | Meaning | Action |
|------------|---------|--------|
| 401 | Unauthorized | Check your Strapi token |
| 403 | Forbidden | Insufficient permissions |
| 404 | Not Found | Endpoint does not exist |
| 500 | Server Error | Strapi internal error |

## Strapi API Token Setup

1. Go to Strapi admin panel: `http://localhost:1337/admin`
2. Navigate to **Settings → API Tokens**
3. Click **Create new API Token**
4. Configure:
   - **Name**: Frontend App
   - **Token duration**: Unlimited (for development)
   - **Token type**: Full access (or customize permissions)
5. Copy the generated token
6. Add to `.env.local`:
   ```
   NEXT_PUBLIC_STRAPI_TOKEN=your-token-here
   ```

## Testing the Integration

1. Make sure Strapi is running:
   ```bash
   cd packages/strapi
   pnpm dev
   ```

2. Start the front app:
   ```bash
   cd packages/front
   pnpm dev
   ```

3. Visit `http://localhost:3000` and check:
   - Environment config shows "Has Token: ✅ Yes"
   - Video background data loads successfully
   - Check browser console for API logs

## Troubleshooting

### "Unauthorized" Error
- Verify `NEXT_PUBLIC_STRAPI_TOKEN` is set in `.env.local`
- Check token is valid in Strapi admin
- Restart the dev server after changing env vars

### "No video data found"
- Make sure you have created the video-url content in Strapi admin
- Verify the content is published (not draft)
- Check Strapi permissions for the video-url endpoint

### CORS Errors
- Ensure Strapi CORS is configured to allow your frontend URL
- Check `packages/strapi/config/middlewares.ts`

### Network Errors
- Verify Strapi is running on the correct port
- Check `NEXT_PUBLIC_API_URL` matches your Strapi URL
- Check browser network tab for actual request URLs

