import { api } from "./client"

export type UserTenant = {
  id: number
  name: string
  status: string
}

export type User = {
  id: number
  username: string
  email: string
  first_name?: string
  last_name?: string
  is_active: boolean
  is_staff: boolean
  is_superuser: boolean
  tenants?: UserTenant[]
}

export type CreateUserInput = {
  username: string
  email: string
  password: string
  first_name?: string
  last_name?: string
  is_active?: boolean
  is_staff?: boolean
  is_superuser?: boolean
}

export type UpdateUserInput = Partial<Omit<CreateUserInput, "password">> & {
  password?: string
}

export function listUsers(): Promise<User[]> {
  return api.request("/users/")
}

export function createUser(payload: CreateUserInput): Promise<User> {
  return api.request("/users/", {
    method: "POST",
    body: JSON.stringify(payload),
  })
}

export function updateUser(id: number, payload: UpdateUserInput): Promise<User> {
  return api.request(`/users/${id}/`, {
    method: "PATCH",
    body: JSON.stringify(payload),
  })
}

export function deleteUser(id: number): Promise<void> {
  return api.request(`/users/${id}/`, { method: "DELETE" })
}

export function resetPassword(userId: number, password: string): Promise<{ detail: string }> {
  return api.request(`/users/${userId}/reset-password/`, {
    method: "POST",
    body: JSON.stringify({ password }),
  })
}

export function changePassword(newPassword: string, confirmPassword: string): Promise<{ detail: string }> {
  return api.request(`/users/change-password/`, {
    method: "POST",
    body: JSON.stringify({ new_password: newPassword, confirm_password: confirmPassword }),
  })
}
