import { apiFetch } from "./http";
import type {
  ChangePasswordRequest,
  ChangePasswordResponse,
  CreateUserRequest,
  LoginResponse,
  UpdateProfileRequest,
  UserProfile,
  UserRecord,
} from "./types";

export function login(username: string, password: string): Promise<LoginResponse> {
  return apiFetch<LoginResponse>("/api/auth/login", {
    method: "POST",
    body: JSON.stringify({ username, password }),
  });
}

export function getCurrentUser(): Promise<UserProfile> {
  return apiFetch<UserProfile>("/api/auth/me");
}

export function listUsers(): Promise<UserRecord[]> {
  return apiFetch<UserRecord[]>("/api/auth/users");
}

export function createUser(payload: CreateUserRequest): Promise<UserRecord> {
  return apiFetch<UserRecord>("/api/auth/users", {
    method: "POST",
    body: JSON.stringify(payload),
  });
}

export function updateProfile(payload: UpdateProfileRequest): Promise<UserProfile> {
  return apiFetch<UserProfile>("/api/auth/me", {
    method: "PUT",
    body: JSON.stringify(payload),
  });
}

export function changePassword(payload: ChangePasswordRequest): Promise<ChangePasswordResponse> {
  return apiFetch<ChangePasswordResponse>("/api/auth/me/password", {
    method: "PUT",
    body: JSON.stringify(payload),
  });
}

export function uploadAvatar(file: File): Promise<UserProfile> {
  const formData = new FormData();
  formData.append("file", file);
  return apiFetch<UserProfile>("/api/auth/me/avatar", {
    method: "POST",
    body: formData,
  });
}
