import { queryOptions } from '@tanstack/react-query';
import {
  getPermissionAuditLogs,
  getPermissionCatalog,
  getPermissionTemplate,
  getPermissionTemplates,
  getUserPermissionAssignmentDetail,
  getUserPermissionAssignments
} from './service';
import type {
  PermissionAuditLogFilters,
  PermissionTemplateFilters,
  UserPermissionAssignmentFilters
} from './types';

const permissionManagementAllKey = ['permission-management'] as const;

export const permissionManagementKeys = {
  all: permissionManagementAllKey,
  templates: ['permission-management', 'templates'] as const,
  templateList: (filters: PermissionTemplateFilters) =>
    [...permissionManagementKeys.templates, 'list', filters] as const,
  templateDetail: (id: number) => [...permissionManagementKeys.templates, 'detail', id] as const,
  catalog: [...permissionManagementAllKey, 'catalog'] as const,
  users: ['permission-management', 'users'] as const,
  userList: (filters: UserPermissionAssignmentFilters) =>
    [...permissionManagementKeys.users, 'list', filters] as const,
  userDetail: (userId: string) => [...permissionManagementKeys.users, 'detail', userId] as const,
  auditLogs: ['permission-management', 'audit-logs'] as const,
  auditLogList: (filters: PermissionAuditLogFilters) =>
    [...permissionManagementKeys.auditLogs, 'list', filters] as const
};

export const permissionTemplatesQueryOptions = (filters: PermissionTemplateFilters) =>
  queryOptions({
    queryKey: permissionManagementKeys.templateList(filters),
    queryFn: () => getPermissionTemplates(filters)
  });

export const permissionTemplateDetailQueryOptions = (id: number) =>
  queryOptions({
    queryKey: permissionManagementKeys.templateDetail(id),
    queryFn: () => getPermissionTemplate(id)
  });

export const permissionCatalogQueryOptions = () =>
  queryOptions({
    queryKey: permissionManagementKeys.catalog,
    queryFn: getPermissionCatalog
  });

export const userPermissionAssignmentsQueryOptions = (filters: UserPermissionAssignmentFilters) =>
  queryOptions({
    queryKey: permissionManagementKeys.userList(filters),
    queryFn: () => getUserPermissionAssignments(filters)
  });

export const userPermissionAssignmentDetailQueryOptions = (userId: string) =>
  queryOptions({
    queryKey: permissionManagementKeys.userDetail(userId),
    queryFn: () => getUserPermissionAssignmentDetail(userId)
  });

export const permissionAuditLogsQueryOptions = (filters: PermissionAuditLogFilters) =>
  queryOptions({
    queryKey: permissionManagementKeys.auditLogList(filters),
    queryFn: () => getPermissionAuditLogs(filters)
  });
