---
globs: src/services/*.js,src/infrastructure/*.js
---

# API Patterns và Service Layer

## API Client Configuration
Sử dụng [apiClient.js](mdc:src/infrastructure/apiClient.js) làm base client với:
- Automatic token handling
- Response interceptors cho 401/403 errors
- Consistent error handling

## Service Layer Pattern
Mỗi service nên follow pattern này:

```javascript
// services/userService.js
import apiClient from '@/infrastructure/apiClient'
import { apiPaths } from '@/infrastructure/apiPath'

export const userService = {
  // GET methods
  async getUsers(params = {}) {
    try {
      const response = await apiClient.get(apiPaths.user.list, { params })
      return response.data
    } catch (error) {
      console.error('Error fetching users:', error)
      throw error
    }
  },

  // POST methods
  async createUser(userData) {
    try {
      const response = await apiClient.post(apiPaths.user.create, userData)
      return response.data
    } catch (error) {
      console.error('Error creating user:', error)
      throw error
    }
  },

  // PUT methods
  async updateUser(id, userData) {
    try {
      const response = await apiClient.put(`${apiPaths.user.update}/${id}`, userData)
      return response.data
    } catch (error) {
      console.error('Error updating user:', error)
      throw error
    }
  },

  // DELETE methods
  async deleteUser(id) {
    try {
      const response = await apiClient.delete(`${apiPaths.user.delete}/${id}`)
      return response.data
    } catch (error) {
      console.error('Error deleting user:', error)
      throw error
    }
  }
}
```

## API Paths Organization
Sử dụng [apiPath.js](mdc:src/infrastructure/apiPath.js) để centralize API endpoints:

```javascript
export const apiPaths = {
  user: {
    list: '/api/users',
    create: '/api/users',
    update: '/api/users',
    delete: '/api/users',
    detail: '/api/users'
  },
  order: {
    list: '/api/orders',
    create: '/api/orders',
    // ...
  }
}
```

## Error Handling Patterns
```javascript
// Trong service
const handleApiError = (error, context) => {
  if (error.response) {
    // Server responded with error status
    const { status, data } = error.response
    console.error(`${context} failed:`, { status, data })
    
    switch (status) {
      case 400:
        throw new Error(data.message || 'Bad Request')
      case 401:
        // Token expired - handled by interceptor
        throw new Error('Unauthorized')
      case 403:
        // Forbidden - handled by interceptor
        throw new Error('Forbidden')
      case 404:
        throw new Error('Resource not found')
      case 500:
        throw new Error('Internal server error')
      default:
        throw new Error(data.message || 'Unknown error')
    }
  } else if (error.request) {
    // Network error
    console.error(`${context} network error:`, error.request)
    throw new Error('Network error - please check your connection')
  } else {
    // Other error
    console.error(`${context} error:`, error.message)
    throw error
  }
}
```

## Loading States
```javascript
// Trong component
const isLoading = ref(false)
const error = ref(null)

const fetchData = async () => {
  try {
    isLoading.value = true
    error.value = null
    data.value = await userService.getUsers()
  } catch (err) {
    error.value = err.message
  } finally {
    isLoading.value = false
  }
}
```

## Response Data Structure
API responses nên follow structure:
```javascript
{
  success: true,
  data: {}, // hoặc []
  message: "Success message",
  errors: [] // nếu có validation errors
}
```