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

export const rbacKeys = {
  permissions: ['permissions'] as const,
  roles: ['roles'] as const,
  roleList: (params: PaginationInput) => ['roles', 'list', params] as const,
  role: (id: string) => ['roles', id] as const,
  userRoles: (userId: string) => ['users', userId, 'roles'] as const,
  myPermissions: ['me', 'permissions'] as const,
}

export function permissionListOptions() {
  return queryOptions({
    queryKey: rbacKeys.permissions,
    queryFn: () => api.get<{ data: Permission[] }>('/v1/permissions'),
  })
}

/** All roles (for dropdowns, selectors) */
export function roleListOptions() {
  return queryOptions({
    queryKey: rbacKeys.roles,
    queryFn: () => api.get<{ data: Role[] }>('/v1/roles/all'),
  })
}

/** Paginated roles (for the roles list page) */
export function rolePageOptions(params: PaginationInput) {
  return queryOptions({
    queryKey: rbacKeys.roleList(params),
    queryFn: () => api.get<PaginatedResponse<Role>>('/v1/roles', params as Record<string, unknown>),
  })
}

export function roleDetailOptions(id: string) {
  return queryOptions({
    queryKey: rbacKeys.role(id),
    queryFn: () => api.get<Role & { permissions: string[] }>(`/v1/roles/${id}`),
  })
}

export function myPermissionsOptions() {
  return queryOptions({
    queryKey: rbacKeys.myPermissions,
    queryFn: () => api.get<{ permissions: string[]; roles: { id: string; name: string; slug: string }[] }>('/v1/me/permissions'),
  })
}

export const rbacMutations = {
  createRole: (data: Record<string, unknown>) =>
    api.post<Role>('/v1/roles', data),

  updateRole: (id: string, data: Record<string, unknown>) =>
    api.patch<Role>(`/v1/roles/${id}`, data),

  deleteRole: (id: string) =>
    api.del<Role>(`/v1/roles/${id}`),

  assignRole: (userId: string, roleId: string) =>
    api.post(`/v1/users/${userId}/roles`, { roleId }),

  removeRole: (userId: string, roleId: string) =>
    api.del(`/v1/users/${userId}/roles/${roleId}`),
}
