import Logger from 'src/application/logging/logger';
import { FormType } from '@spiffy-ai/commerce-api-client';
import { ApiFormResponseAttributes } from 'src/application/models/api/responseGenerics';
import { hasPropertyOfType } from 'src/application/models/guards/utils';

const logger = new Logger('isApiFormResponse');

/**
 * Type guard to check if the provided data has the all of the properties (with the correct types) of
 * a FormResponseAttribute
 *
 * @param data - The data to check
 *
 * @returns true if the data has the correct properties, false otherwise
 */
export const isApiFormResponseAttributes = (data: unknown): data is ApiFormResponseAttributes => {
  if (data == null || typeof data !== 'object') {
    logger.logError('isApiFormResponseAttributes: data is null or not an object', undefined, {
      data,
    });
    return false;
  }

  if ('form_category' in data && typeof data.form_category !== 'object') {
    logger.logError('isApiFormResponseAttributes: form_category is not an object', undefined, {
      data,
    });
    return false;
  }

  if ('form_category' in data && typeof data.form_category === 'object') {
    if (
      !hasPropertyOfType(data.form_category, 'form_type', 'string') ||
      !Object.values(FormType).includes(data.form_category.form_type as FormType)
    ) {
      logger.logError(
        'isApiFormResponseAttributes: form_type is missing or not a valid form type',
        undefined,
        {
          data,
        },
      );
      return false;
    }
  }

  if (!hasPropertyOfType(data, 'schema', 'object')) {
    logger.logError('isApiFormResponseAttributes: schema is missing or not an object', undefined, {
      data,
    });
    return false;
  }

  // TODO: also wanna validate the fields of data.schema.properties but might wanna change the schema
  // to not have the property name as a key in the object
  if (!hasPropertyOfType(data.schema, 'properties', 'object')) {
    logger.logError(
      'isApiFormResponseAttributes: schema.properties is missing or not an object',
      undefined,
      {
        data,
      },
    );
    return false;
  }

  if (!hasPropertyOfType(data.schema, 'required', 'array')) {
    logger.logError(
      'isApiFormResponseAttributes: schema.required is missing or not an array',
      undefined,
      { data },
    );
    return false;
  }

  if (
    !data.schema.required.every(
      (key: unknown) => typeof key === 'string' && key in data.schema.properties,
    )
  ) {
    logger.logError(
      'isApiFormResponseAttributes: schema.required contains invalid property keys',
      undefined,
      {
        data,
      },
    );
    return false;
  }

  return true;
};
