/**
 * @aurora-catalyst-generated
 * @source cliter/iam/permission.aurora.yaml
 */
import { type ResolveFn } from '@angular/router';
import {
  buildSortOrder,
  DEFAULT_PAGE_SIZE,
  getRelationIncludes,
  queryFindById,
  queryPaginate,
  type DataTableData,
} from '@aurora';
import { type IamBoundedContext, type IamPermission } from '@src/src/app/aurora.types';
import { forkJoin, map } from 'rxjs';
import { BOUNDED_CONTEXT_LIST_CONFIG } from '../../bounded-context/data-access/bounded-context.list-config';
import { getPermissionStandaloneColumns } from '../permission.columns';
import { PERMISSION_DETAIL_CONFIG } from './permission.detail-config';
import { PERMISSION_LIST_CONFIG } from './permission.list-config';
export const permissionListResolver: ResolveFn<{
  pagination: DataTableData<IamPermission>;
  boundedContextOptions: IamBoundedContext[];
}> = () => {
  const { queryPagination, paginationKey, fields } = PERMISSION_LIST_CONFIG;
  const include = getRelationIncludes(getPermissionStandaloneColumns());
  const pagination$ = queryPaginate<IamPermission>(queryPagination, paginationKey, fields, {
    query: {
      offset: 0,
      limit: DEFAULT_PAGE_SIZE,
      order: buildSortOrder([]),
      include: include.length > 0 ? include : undefined,
    },
  });
  const boundedContextOptions$ = queryPaginate<IamBoundedContext>(
    BOUNDED_CONTEXT_LIST_CONFIG.queryPagination,
    BOUNDED_CONTEXT_LIST_CONFIG.paginationKey,
    BOUNDED_CONTEXT_LIST_CONFIG.fields,
    { query: { offset: 0, limit: 1000, order: buildSortOrder([]) } },
  ).pipe(map((d) => d.rows));
  return forkJoin({ pagination: pagination$, boundedContextOptions: boundedContextOptions$ });
};

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

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