import { apiClient } from '@/services/api/client';

// FE-PAGE-013: Add Search page - Search Service
// FE-API-008: Search service integration

export interface SearchUsersParams {
  query?: string;
  page?: number;
  limit?: number;
}

export interface SearchUsersResponse {
  users: Array<{
    id: string;
    username: string;
    email: string;
    first_name?: string;
    last_name?: string;
    avatar_url?: string;
    bio?: string;
    created_at: string;
  }>;
  total: number;
  page?: number;
  limit?: number;
}

/**
 * Search users by username, email, first_name, or last_name
 */
export async function searchUsers(
  params: SearchUsersParams,
): Promise<SearchUsersResponse> {
  const queryParams = new URLSearchParams();
  if (params.query) queryParams.append('q', params.query);
  if (params.page) queryParams.append('page', params.page.toString());
  if (params.limit) queryParams.append('limit', params.limit.toString());

  const response = await apiClient.get<{
    users: SearchUsersResponse['users'];
    total: number;
    data?: {
      users?: SearchUsersResponse['users'];
      pagination?: {
        total: number;
        page?: number;
        limit?: number;
      };
    };
  }>(`/users/search?${queryParams.toString()}`);
  
  // FIX: La réponse API a une structure imbriquée : { data: { pagination: {...}, users: [] }, success: true }
  let users: SearchUsersResponse['users'] = [];
  let total = 0;

  if (response.data && typeof response.data === 'object') {
    // Vérifier si la structure est imbriquée (response.data.data)
    if ('data' in response.data && response.data.data && typeof response.data.data === 'object') {
      const nestedData = response.data.data;
      // Structure: { data: { pagination: {...}, users: [] } }
      if (nestedData.users && Array.isArray(nestedData.users)) {
        users = nestedData.users;
      }
      if (nestedData.pagination && typeof nestedData.pagination === 'object') {
        total = nestedData.pagination.total || 0;
      }
    } else if ('users' in response.data && Array.isArray((response.data as any).users)) {
      // Structure plate: { users: [], total: ... }
      users = (response.data as any).users;
      total = (response.data as any).total || 0;
    }
  }

  return {
    users: users || [],
    total: total || 0,
    page: params.page || 1,
    limit: params.limit || 20,
  };
}
