import type { LocationQueryValue } from 'vue-router';
import { request } from '../request';
import { type ServiceRequestResult, safeJsonRequestConfig } from './shared';
import { type BackendObjectContextDTO, normalizeObjectContext } from './object-context-normalize';

function createContextApiUrl(config: App.ObjectContext.DomainConfig, objectId: string) {
  if (config.contextApiObjectIdPlacement !== 'path') {
    return config.contextApiPath;
  }

  const placeholder = `{${config.contextApiObjectIdParamKey}}`;

  return config.contextApiPath.replace(placeholder, encodeURIComponent(objectId));
}

export async function fetchGetObjectContext(
  config: App.ObjectContext.DomainConfig,
  objectId: string
): Promise<ServiceRequestResult<Api.ObjectContext.ContextInfo>> {
  const result = await request<BackendObjectContextDTO>({
    ...safeJsonRequestConfig,
    url: createContextApiUrl(config, objectId),
    method: 'get',
    params:
      config.contextApiObjectIdPlacement === 'path'
        ? undefined
        : ({
            [config.contextApiObjectIdParamKey]: objectId
          } satisfies Record<string, LocationQueryValue | LocationQueryValue[]>)
  });

  if (result.error || !result.data) {
    return result as ServiceRequestResult<Api.ObjectContext.ContextInfo>;
  }

  return {
    ...result,
    data: normalizeObjectContext(config, objectId, result.data)
  };
}
