import { BffCatalogEntity, BffCatalogRelatedEntity } from '../../types';

type CatalogEntitySchemaProps = {
  entity: BffCatalogEntity;
  relatedEntity: BffCatalogRelatedEntity | null;
};

export function useCatalogEntitySchema({ entity, relatedEntity }: CatalogEntitySchemaProps) {
  const { schema } = entity.metadata || {};

  let parsedSchema;

  try {
    parsedSchema = JSON.parse(schema);
  } catch (error) {
    parsedSchema = undefined;
  }

  let parsedApiDefinition: Record<string, unknown> | undefined;

  try {
    parsedApiDefinition = relatedEntity?.metadata?.schema
      ? (JSON.parse(relatedEntity.metadata.schema) as Record<string, unknown>)
      : undefined;
  } catch (err) {
    parsedApiDefinition = undefined;
  }

  const definition: Record<string, unknown> =
    !parsedApiDefinition || relatedEntity?.metadata?.specType !== 'openapi'
      ? {
          openapi: '3.0.0',
          info: { version: '1', description: 'test', title: 'test' },
          paths: {},
          components: {
            schemas: {},
          },
        }
      : parsedApiDefinition;

  return {
    definition,
    parsedSchema,
    rawSchema: schema,
  };
}
