/**
 * @aurora-catalyst-generated
 * @source cliter/iam/tenant.aurora.yaml
 */
import { type ResolveFn } from '@angular/router';
import {
  buildSortOrder,
  DEFAULT_PAGE_SIZE,
  getRelationIncludes,
  queryFindById,
  queryPaginate,
  type DataTableData,
} from '@aurora';
import { type IamTenant } from '@src/src/app/aurora.types';
import { forkJoin, map } from 'rxjs';
import { TENANT_LIST_CONFIG } from '../../tenant/data-access/tenant.list-config';
import { getTenantStandaloneColumns } from '../tenant.columns';
import { TENANT_DETAIL_CONFIG } from './tenant.detail-config';
export const tenantListResolver: ResolveFn<{
  pagination: DataTableData<IamTenant>;
  parentOptions: IamTenant[];
}> = () => {
  const { queryPagination, paginationKey, fields } = TENANT_LIST_CONFIG;
  const include = getRelationIncludes(getTenantStandaloneColumns());
  const pagination$ = queryPaginate<IamTenant>(queryPagination, paginationKey, fields, {
    query: {
      offset: 0,
      limit: DEFAULT_PAGE_SIZE,
      order: buildSortOrder([]),
      include: include.length > 0 ? include : undefined,
    },
  });
  const parentOptions$ = queryPaginate<IamTenant>(
    TENANT_LIST_CONFIG.queryPagination,
    TENANT_LIST_CONFIG.paginationKey,
    TENANT_LIST_CONFIG.fields,
    { query: { offset: 0, limit: 1000, order: buildSortOrder([]) } },
  ).pipe(map((d) => d.rows));
  return forkJoin({ pagination: pagination$, parentOptions: parentOptions$ });
};

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

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