import { WEB_SERVICE_PREFIX } from './service';

export const OBJECT_CONTEXT_QUERY_KEY = 'objectId' as const;

export const objectContextDomainConfigs: App.ObjectContext.DomainConfig[] = [
  {
    domainKey: 'project',
    mode: 'object-context',
    objectType: 'project',
    routePathPrefixes: ['/project'],
    entryRouteKey: 'project_list',
    entryRoutePath: '/project/list',
    fallbackDefaultRouteKey: 'project_project_overview',
    fallbackDefaultRoutePath: '/project/project/overview',
    contextApiPath: `${WEB_SERVICE_PREFIX}/project/project/{id}/context`,
    contextApiObjectIdParamKey: 'id',
    contextApiObjectIdPlacement: 'path',
    objectIdQueryKey: OBJECT_CONTEXT_QUERY_KEY
  },
  {
    domainKey: 'product',
    mode: 'object-context',
    objectType: 'product',
    routePathPrefixes: ['/product'],
    entryRouteKey: 'product_list',
    entryRoutePath: '/product/list',
    fallbackDefaultRouteKey: 'product_dashboard',
    fallbackDefaultRoutePath: '/product/dashboard',
    contextApiPath: `${WEB_SERVICE_PREFIX}/project/product/{id}/context`,
    contextApiObjectIdParamKey: 'id',
    contextApiObjectIdPlacement: 'path',
    objectIdQueryKey: OBJECT_CONTEXT_QUERY_KEY
  }
];

function normalizePath(path: string) {
  if (!path) {
    return '/';
  }

  return path.endsWith('/') && path !== '/' ? path.slice(0, -1) : path;
}

function isPathMatchedByPrefix(path: string, prefix: string) {
  const normalizedPath = normalizePath(path);
  const normalizedPrefix = normalizePath(prefix);

  return normalizedPath === normalizedPrefix || normalizedPath.startsWith(`${normalizedPrefix}/`);
}

export function getObjectContextDomainConfigByPath(path: string) {
  return objectContextDomainConfigs.find(config =>
    config.routePathPrefixes.some(prefix => isPathMatchedByPrefix(path, prefix))
  );
}

export function isObjectContextEntryPath(path: string, config: App.ObjectContext.DomainConfig) {
  return normalizePath(path) === normalizePath(config.entryRoutePath);
}
