/**
 * @aurora-catalyst-generated
 * @source cliter/iam/role.aurora.yaml
 */
import { type ResolveFn } from '@angular/router';
import {
  buildSortOrder,
  DEFAULT_PAGE_SIZE,
  queryFindById,
  queryPaginate,
  type DataTableData,
} from '@aurora';
import { type IamPermission, type IamRole } from '@src/src/app/aurora.types';
import { forkJoin, map } from 'rxjs';
import { PERMISSION_LIST_CONFIG } from '../../permission/data-access/permission.list-config';
import { ROLE_DETAIL_CONFIG } from './role.detail-config';
import { ROLE_LIST_CONFIG } from './role.list-config';
export const roleListResolver: ResolveFn<{
  pagination: DataTableData<IamRole>;
  permissionOptions: IamPermission[];
}> = () => {
  const { queryPagination, paginationKey, fields } = ROLE_LIST_CONFIG;
  const pagination$ = queryPaginate<IamRole>(queryPagination, paginationKey, fields, {
    query: {
      offset: 0,
      limit: DEFAULT_PAGE_SIZE,
      order: buildSortOrder([]),
    },
  });
  const permissionOptions$ = queryPaginate<IamPermission>(
    PERMISSION_LIST_CONFIG.queryPagination,
    PERMISSION_LIST_CONFIG.paginationKey,
    PERMISSION_LIST_CONFIG.fields,
    { query: { offset: 0, limit: 1000, order: buildSortOrder([]) } },
  ).pipe(map((d) => d.rows));
  return forkJoin({ pagination: pagination$, permissionOptions: permissionOptions$ });
};

export const roleNewResolver: ResolveFn<{
  permissionOptions: IamPermission[];
}> = () => {
  const permissionOptions$ = queryPaginate<IamPermission>(
    PERMISSION_LIST_CONFIG.queryPagination,
    PERMISSION_LIST_CONFIG.paginationKey,
    PERMISSION_LIST_CONFIG.fields,
    { query: { offset: 0, limit: 1000, order: buildSortOrder([]) } },
  ).pipe(map((d) => d.rows));
  return forkJoin({ permissionOptions: permissionOptions$ });
};

export const roleDetailResolver: ResolveFn<
  {
    item: IamRole | null;
    permissionOptions: IamPermission[];
  } | null
> = (route) => {
  const id = route.paramMap.get('id');
  if (!id) return null;
  const { queryObject, objectKey, fields } = ROLE_DETAIL_CONFIG;
  const item$ = queryFindById<IamRole>(queryObject, objectKey, id, fields);
  const permissionOptions$ = queryPaginate<IamPermission>(
    PERMISSION_LIST_CONFIG.queryPagination,
    PERMISSION_LIST_CONFIG.paginationKey,
    PERMISSION_LIST_CONFIG.fields,
    { query: { offset: 0, limit: 1000, order: buildSortOrder([]) } },
  ).pipe(map((d) => d.rows));
  return forkJoin({ item: item$, permissionOptions: permissionOptions$ });
};
