/**
 * Users API
 *
 * Endpoints for user management (admin/manager only)
 */

import { get, post, patch, del } from './client';
import type {
  UserResponse,
  UserListResponse,
  CreateUserRequest,
  UpdateUserRequest,
  SuccessResponse,
} from '@/types/api';

/**
 * List users with pagination
 * GET /api/v1/users?page=1&limit=20&role=user&organizationId=xxx
 * Requires: ADMIN or MANAGER role
 */
export async function listUsers(params?: {
  page?: number;
  limit?: number;
  role?: string;
  organizationId?: string;
}): Promise<UserListResponse> {
  const queryParams = new URLSearchParams();
  if (params?.page) queryParams.append('page', params.page.toString());
  if (params?.limit) queryParams.append('limit', params.limit.toString());
  if (params?.role) queryParams.append('role', params.role);
  if (params?.organizationId) queryParams.append('organizationId', params.organizationId);

  const queryString = queryParams.toString();
  return get<UserListResponse>(`/api/v1/users${queryString ? `?${queryString}` : ''}`);
}

/**
 * Get user by ID
 * GET /api/v1/users/:id
 * Requires: ADMIN or MANAGER role
 */
export async function getUser(id: string): Promise<UserResponse> {
  return get<UserResponse>(`/api/v1/users/${id}`);
}

/**
 * Create new user
 * POST /api/v1/users
 * Requires: ADMIN role
 */
export async function createUser(data: CreateUserRequest): Promise<UserResponse> {
  return post<UserResponse>('/api/v1/users', data);
}

/**
 * Update user
 * PATCH /api/v1/users/:id
 * Requires: ADMIN or MANAGER role
 */
export async function updateUser(id: string, data: UpdateUserRequest): Promise<UserResponse> {
  return patch<UserResponse>(`/api/v1/users/${id}`, data);
}

/**
 * Delete user (soft delete)
 * DELETE /api/v1/users/:id
 * Requires: ADMIN role
 */
export async function deleteUser(id: string): Promise<SuccessResponse> {
  return del<SuccessResponse>(`/api/v1/users/${id}`);
}

/**
 * Restore soft-deleted user
 * POST /api/v1/users/:id/restore
 * Requires: ADMIN role
 */
export async function restoreUser(id: string): Promise<UserResponse> {
  return post<UserResponse>(`/api/v1/users/${id}/restore`);
}

/**
 * Change own password
 * PATCH /api/v1/users/me/password
 * Requires: Authentication
 */
export async function changePassword(data: {
  currentPassword: string;
  newPassword: string;
}): Promise<{ message: string }> {
  return patch<{ message: string }>('/api/v1/users/me/password', data);
}
