import { apiClient } from '@/lib/api-client';

export interface BackofficeUser {
  id: string;
  email: string;
  fullName: string;
  role: 'ADMIN' | 'SUPERVISOR' | 'STAFF' | 'AGENT';
  status: 'ACTIVE' | 'INACTIVE';
  lastLogin?: string;
  createdAt: string;
  updatedAt: string;
}

export const usersApi = {
  getAll: async (filters?: { search?: string; role?: string; status?: string; page?: number; pageSize?: number }) => {
    const params = new URLSearchParams();
    if (filters?.search) params.append('search', filters.search);
    if (filters?.role) params.append('role', filters.role);
    if (filters?.status) params.append('status', filters.status);
    if (filters?.page) params.append('page', filters.page.toString());
    if (filters?.pageSize) params.append('pageSize', filters.pageSize.toString());

    const response = await apiClient.get<any>(`/auth/users?${params.toString()}`);
    
    // Handle different response formats
    if (response && typeof response === 'object') {
      if ('items' in response) {
        return response as { items: BackofficeUser[]; total: number };
      }
      if (Array.isArray(response)) {
        return { items: response as BackofficeUser[], total: response.length };
      }
    }
    
    return { items: Array.isArray(response) ? response : [], total: 0 };
  },

  getById: (id: string) => {
    return apiClient.get<BackofficeUser>(`/auth/users/${id}`);
  },

  create: (data: { email: string; fullName: string; role: string; password: string }) => {
    return apiClient.post<BackofficeUser>('/auth/users', data);
  },

  update: (id: string, data: Partial<BackofficeUser>) => {
    return apiClient.patch<BackofficeUser>(`/auth/users/${id}`, data);
  },

  delete: (id: string) => {
    return apiClient.delete<void>(`/auth/users/${id}`);
  },

  resetPassword: (id: string, tempPassword: string) => {
    return apiClient.post<{ success: boolean; message: string }>(`/auth/users/${id}/reset-password`, {
      tempPassword,
    });
  },
};
