import { isApiOrgConfigResults } from 'src/application/models/guards/api/isApiOrgConfigResults';
import { OrgConfig } from 'src/application/models/api/orgConfigResults';
import { validateOrganizationConfig } from 'src/application/models/validators/validateOrganizationConfig';
import { OrganizationConfig } from 'src/application/models/api/organizationConfig';

/**
 *
 * @param data
 * @returns
 */
export const validateOrgConfigResults = (data: unknown): OrgConfig | undefined => {
  if (!isApiOrgConfigResults(data)) {
    return undefined;
  }

  return {
    configs: data.configs
      .map(config => validateOrganizationConfig(config))
      .filter((config): config is OrganizationConfig => config != null),
    experiments: data.experiments.map(experiment => ({
      group: experiment.group,
      groupName: experiment.group_name,
      name: experiment.name,
      ruleId: experiment.rule_id,
      // TODO this needs to be strongly typed but we're not running any experiments at the moment
      value: experiment.value as Record<string, unknown>,
    })),
    gates: data.gates.map(gate => ({
      groupName: gate.group_name,
      name: gate.name,
      ruleId: gate.rule_id,
      value: gate.value,
    })),
    org: {
      org: {
        id: data.org.org.id,
        displayName: data.org.org.display_name,
        domain: data.org.org.domain,
        shortName: data.org.org.short_name,
        status: data.org.org.status,
        createdAt: data.org.org.created_at?.toISOString(),
        updatedAt: data.org.org.updated_at?.toISOString(),
      },
      settings: {},
    },
  };
};
