import Logger from 'src/application/logging/logger';
import { Response, ResponseCategory } from '@spiffy-ai/commerce-api-client';
import { hasPropertyOfType } from 'src/application/models/guards/utils';

const logger = new Logger('isApiResponse');

export const isApiResponse = (data: unknown): data is Response => {
  if (data == null || typeof data !== 'object') {
    logger.logError('isApiResponse: data is null or not an object', undefined, { data });
    return false;
  }

  if (!hasPropertyOfType(data, 'id', 'string')) {
    logger.logError('isApiResponse: id is not a string', undefined, { data });
    return false;
  }

  if (
    !hasPropertyOfType(data, 'category', 'string') ||
    !Object.values(ResponseCategory).includes(data.category as ResponseCategory)
  ) {
    logger.logError(
      'isApiResponse: category is not a string or not a valid response category',
      undefined,
      { data },
    );
    return false;
  }

  if (!hasPropertyOfType(data, 'created_at', 'string')) {
    logger.logError('isApiResponse: created_at is not a string', undefined, { data });
    return false;
  }

  if (!hasPropertyOfType(data, 'attributes', 'object', true)) {
    logger.logError('isApiResponse: attributes is not an object', undefined, { data });
    return false;
  }

  return true;
};
