import { queryOptions } from '@tanstack/react-query'
import { api } from '@/lib/api-client'
import type { PaginationInput, PaginatedResponse } from '@lunarfront/shared/schemas'

export interface UserRole {
  id: string
  name: string
  slug: string
  isSystem: boolean
}

export interface UserRecord {
  id: string
  email: string
  firstName: string
  lastName: string
  role: string
  isActive: boolean
  createdAt: string
  roles: UserRole[]
}

export const userKeys = {
  list: (params: PaginationInput) => ['users', params] as const,
  roles: (userId: string) => ['users', userId, 'roles'] as const,
}

export function userListOptions(params: PaginationInput) {
  return queryOptions({
    queryKey: userKeys.list(params),
    queryFn: () => api.get<PaginatedResponse<UserRecord>>('/v1/users', params as Record<string, unknown>),
  })
}

export function userRolesOptions(userId: string) {
  return queryOptions({
    queryKey: userKeys.roles(userId),
    queryFn: () => api.get<{ data: UserRole[] }>(`/v1/users/${userId}/roles`),
  })
}

export const userMutations = {
  toggleStatus: (userId: string, isActive: boolean) =>
    api.patch<{ id: string; isActive: boolean }>(`/v1/users/${userId}/status`, { isActive }),
}
