import { apiClient } from '@/lib/api-client';
import type {
  UserFilters,
  UserMasterOptionsResponse,
  UserMutationPayload,
  UsersResponse
} from './types';

function createQueryString(filters: UserFilters) {
  const params = new URLSearchParams();

  if (filters.page) params.set('page', String(filters.page));
  if (filters.limit) params.set('limit', String(filters.limit));
  if (filters.roles) params.set('roles', filters.roles);
  if (filters.search) params.set('search', filters.search);
  if (filters.sort) params.set('sort', filters.sort);

  return params.toString();
}

export async function getUsers(filters: UserFilters): Promise<UsersResponse> {
  const queryString = createQueryString(filters);
  return apiClient<UsersResponse>(`/users${queryString ? `?${queryString}` : ''}`);
}

export async function getUserMasterOptions(): Promise<UserMasterOptionsResponse> {
  return apiClient<UserMasterOptionsResponse>('/users?mode=options');
}

export async function createUser(data: UserMutationPayload) {
  return apiClient<{ success: boolean; message: string; user_id: string }>('/users', {
    method: 'POST',
    body: JSON.stringify(data)
  });
}

export async function updateUser(id: string, data: UserMutationPayload) {
  return apiClient<{ success: boolean; message: string }>(`/users/${id}`, {
    method: 'PATCH',
    body: JSON.stringify(data)
  });
}

export async function deleteUser(id: string) {
  return apiClient<{ success: boolean; message: string }>(`/users/${id}`, {
    method: 'DELETE'
  });
}
