import client from './client';
import type { UserInfo } from './auth';
import type { PaginatedResponse } from './types';

export interface CreateUserRequest {
  username: string;
  password: string;
  email?: string;
  phone?: string;
  display_name?: string;
}

export interface UpdateUserRequest {
  email?: string;
  phone?: string;
  display_name?: string;
  status?: string;
  version: number;
}

export async function listUsers(page = 1, pageSize = 20, search = '') {
  const { data } = await client.get<{ success: boolean; data: PaginatedResponse<UserInfo> }>(
    '/users',
    { params: { page, page_size: pageSize, search: search || undefined } }
  );
  return data.data;
}

export async function getUser(id: string) {
  const { data } = await client.get<{ success: boolean; data: UserInfo }>(`/users/${id}`);
  return data.data;
}

export async function createUser(req: CreateUserRequest) {
  const { data } = await client.post<{ success: boolean; data: UserInfo }>('/users', req);
  return data.data;
}

export async function updateUser(id: string, req: UpdateUserRequest) {
  const { data } = await client.put<{ success: boolean; data: UserInfo }>(`/users/${id}`, req);
  return data.data;
}

export async function deleteUser(id: string) {
  await client.delete(`/users/${id}`);
}

export async function assignRoles(userId: string, roleIds: string[]) {
  await client.post(`/users/${userId}/roles`, { role_ids: roleIds });
}

export async function resetPassword(id: string, req: { new_password: string; version: number }) {
  await client.post(`/users/${id}/reset-password`, req);
}
