import { api } from './client';
import type { ApiResponse, UserDetail, UserFilters, PaginatedResult, UserRole } from '../../types';

export interface CreateUserRequest {
  email: string;
  password: string;
  fullName: string;
  role: UserRole;
  avatarUrl?: string;
}

export interface UpdateUserRequest {
  fullName?: string;
  role?: UserRole;
  isActive?: boolean;
  avatarUrl?: string | null;
}

export interface ResetPasswordRequest {
  newPassword: string;
}

export const usersApi = {
  list: (filters?: UserFilters) => {
    const params = new URLSearchParams();
    if (filters?.role) params.append('role', filters.role);
    if (filters?.isActive !== undefined) params.append('isActive', String(filters.isActive));
    if (filters?.search) params.append('search', filters.search);
    if (filters?.page) params.append('page', String(filters.page));
    if (filters?.limit) params.append('limit', String(filters.limit));

    return api.get<ApiResponse<PaginatedResult<UserDetail>>>(`/users?${params.toString()}`);
  },

  getById: (id: string) =>
    api.get<ApiResponse<UserDetail>>(`/users/${id}`),

  create: (data: CreateUserRequest) =>
    api.post<ApiResponse<UserDetail>>('/users', data),

  update: (id: string, data: UpdateUserRequest) =>
    api.patch<ApiResponse<UserDetail>>(`/users/${id}`, data),

  delete: (id: string) =>
    api.delete<ApiResponse<null>>(`/users/${id}`),

  resetPassword: (id: string, data: ResetPasswordRequest) =>
    api.patch<ApiResponse<null>>(`/users/${id}/reset-password`, data),
};
