# API Structure & React Query Implementation

This document outlines the organized API calling structure using TanStack Query (React Query) in the Voice Cast Admin Panel.

## Folder Structure

```
src/
├── lib/
│   └── api.ts                 # Base API configuration with axios
├── types/
│   └── api.ts                 # TypeScript interfaces for API entities
├── services/
│   ├── users.ts               # User API service functions
│   ├── projects.ts            # Project API service functions
│   └── voice-casts.ts         # Voice Cast API service functions
├── hooks/
│   ├── use-users.ts           # React Query hooks for users
│   ├── use-projects.ts        # React Query hooks for projects
│   ├── use-voice-casts.ts     # React Query hooks for voice casts
│   ├── use-auth.ts            # Authentication hook
│   └── index.ts               # Export all hooks
└── components/
    └── examples/
        ├── users-table.tsx     # Example component using the hooks
        └── auth-example.tsx    # Example authentication component
```

## Key Features

### 1. Base API Configuration (`src/lib/api.ts`)

- Axios instance with interceptors
- Request/response error handling
- **Authentication token management**
- Generic API response types
- **Automatic token injection in requests**

### 2. Type Safety (`src/types/api.ts`)

- Comprehensive TypeScript interfaces
- Request/response type definitions
- Pagination support
- Entity relationships

### 3. Service Layer (`src/services/`)

- Clean separation of concerns
- Reusable API functions
- Consistent error handling
- RESTful endpoint organization

### 4. React Query Hooks (`src/hooks/`)

- Optimistic updates
- Automatic caching and invalidation
- Loading and error states
- Toast notifications for user feedback

### 5. Authentication System (`src/hooks/use-auth.ts`)

- **NextAuth.js integration**
- **Automatic token management**
- **Session state management**
- **Token storage and retrieval**

## Authentication Setup

### Using the Auth Hook

```tsx
import { useAuth } from "@/hooks/use-auth";

function MyComponent() {
  const { session, status, isAuthenticated, user, accessToken } = useAuth();

  if (status === "loading") return <div>Loading...</div>;
  if (!isAuthenticated) return <div>Please log in</div>;

  return (
    <div>
      <h1>Welcome, {user?.name}!</h1>
      <p>Your access token is: {accessToken ? "Available" : "Not available"}</p>
    </div>
  );
}
```

### Token Management

The authentication system automatically:

- Stores tokens in localStorage when user logs in
- Removes tokens when user logs out
- Injects tokens in all API requests
- Handles 401 errors by redirecting to login

## Usage Examples

### Basic Query Hook

```tsx
import { useUsers } from "@/hooks";

function UsersList() {
  const { data, isLoading, error } = useUsers({ page: 1, limit: 10 });

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>Error: {error.message}</div>;

  return (
    <div>
      {data?.data.map((user) => (
        <div key={user.id}>{user.name}</div>
      ))}
    </div>
  );
}
```

### Mutation Hook

```tsx
import { useCreateUser } from "@/hooks";

function CreateUserForm() {
  const createUser = useCreateUser();

  const handleSubmit = async (userData) => {
    try {
      await createUser.mutateAsync(userData);
      // Form will be reset and users list will be refreshed automatically
    } catch (error) {
      // Error is handled automatically with toast notification
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      {/* form fields */}
      <button type="submit" disabled={createUser.isPending}>
        {createUser.isPending ? "Creating..." : "Create User"}
      </button>
    </form>
  );
}
```

### Complex Queries with Dependencies

```tsx
import { useProjectVoiceCasts } from "@/hooks";

function ProjectVoiceCasts({ projectId }) {
  const { data, isLoading } = useProjectVoiceCasts(projectId, {
    page: 1,
    limit: 20,
  });

  // Query automatically refetches when projectId changes
  // Cache is shared between different project queries
}
```

## API Endpoints

### Users

- `GET /api/users` - List users with pagination
- `GET /api/users/:id` - Get user by ID
- `POST /api/users` - Create new user
- `PUT /api/users/:id` - Update user
- `DELETE /api/users/:id` - Delete user
- `GET /api/users/me` - Get current user
- `PUT /api/users/me` - Update current user

### Projects

- `GET /api/projects` - List projects with pagination
- `GET /api/projects/:id` - Get project by ID
- `POST /api/projects` - Create new project
- `PUT /api/projects/:id` - Update project
- `DELETE /api/projects/:id` - Delete project
- `GET /api/users/:id/projects` - Get user's projects
- `POST /api/projects/:id/members` - Add member to project
- `DELETE /api/projects/:id/members/:userId` - Remove member from project
- `PATCH /api/projects/:id/archive` - Archive project
- `PATCH /api/projects/:id/restore` - Restore archived project

### Voice Casts

- `GET /api/voice-casts` - List voice casts with pagination
- `GET /api/voice-casts/:id` - Get voice cast by ID
- `POST /api/voice-casts` - Create new voice cast
- `PUT /api/voice-casts/:id` - Update voice cast
- `DELETE /api/voice-casts/:id` - Delete voice cast
- `GET /api/projects/:id/voice-casts` - Get project's voice casts
- `GET /api/users/:id/voice-casts` - Get user's voice casts
- `GET /api/voice-casts/pending` - Get pending voice casts
- `PATCH /api/voice-casts/:id/approve` - Approve voice cast
- `PATCH /api/voice-casts/:id/reject` - Reject voice cast
- `POST /api/voice-casts/upload` - Upload audio file
- `GET /api/voice-casts/stats` - Get voice cast statistics

## Environment Variables

```env
NEXT_PUBLIC_API_URL=http://localhost:3001/api
```

## Benefits of This Structure

1. **Type Safety**: Full TypeScript support with proper interfaces
2. **Caching**: Automatic caching and invalidation with React Query
3. **Error Handling**: Consistent error handling across all API calls
4. **Loading States**: Built-in loading and pending states
5. **Optimistic Updates**: Immediate UI updates with background sync
6. **Reusability**: Hooks can be used across multiple components
7. **Maintainability**: Clear separation of concerns and organized structure
8. **Developer Experience**: IntelliSense support and easy debugging
9. **Authentication**: Seamless NextAuth.js integration with automatic token management

## Best Practices

1. **Always use the hooks** instead of calling services directly
2. **Handle loading and error states** in your components
3. **Use the toast notifications** for user feedback
4. **Leverage React Query's caching** for better performance
5. **Keep query keys consistent** for proper cache invalidation
6. **Use enabled option** for conditional queries
7. **Implement proper error boundaries** for production apps
8. **Use the useAuth hook** for authentication state management
9. **Never call hooks inside non-React functions** (like axios interceptors)

## Authentication Flow

1. **Login**: User authenticates via NextAuth.js
2. **Token Storage**: Access token is automatically stored in localStorage
3. **API Requests**: All requests automatically include the Bearer token
4. **Token Refresh**: Handled by NextAuth.js session management
5. **Logout**: Token is automatically removed from storage
6. **Error Handling**: 401 responses automatically redirect to login

## Troubleshooting

### Common Issues

1. **"Invalid hook call" error**: Make sure hooks are only called inside React components or custom hooks
2. **Authentication not working**: Check that NextAuth.js is properly configured
3. **API calls failing**: Verify your API URL and token configuration
4. **Token not persisting**: Ensure localStorage is available (not in SSR context)

### Debug Tips

- Use the `AuthExample` component to debug authentication state
- Check browser console for token-related logs
- Verify NextAuth.js session in browser dev tools
- Use React Query DevTools to inspect query states
