import { openApiSchemas } from './platform-operations.generated';
import type { JsonSchema } from './types';

const schemas = openApiSchemas as unknown as Record<string, JsonSchema>;

export function resolveSchema(schema: JsonSchema | null | undefined, seen = new Set<string>()): JsonSchema {
  if (!schema) return {};
  if (schema.$ref) {
    const name = schema.$ref.split('/').at(-1) || '';
    if (seen.has(name)) return { type: 'object', description: schema.description };
    const nextSeen = new Set(seen).add(name);
    return { ...resolveSchema(schemas[name], nextSeen), description: schema.description || schemas[name]?.description };
  }
  const alternatives = schema.oneOf || schema.anyOf;
  if (alternatives?.length) {
    const meaningful = alternatives.find((item) => item.type !== 'null') || alternatives[0];
    return { ...schema, ...resolveSchema(meaningful, seen), oneOf: undefined, anyOf: undefined };
  }
  return schema;
}

export function schemaType(schema: JsonSchema): string {
  const type = resolveSchema(schema).type;
  if (Array.isArray(type)) return type.find((item) => item !== 'null') || 'string';
  return typeof type === 'string' ? type : 'string';
}

export function defaultForSchema(schema: JsonSchema): unknown {
  const resolved = resolveSchema(schema);
  if (resolved.default !== undefined) return resolved.default;
  switch (schemaType(resolved)) {
    case 'boolean': return false;
    case 'array': return [];
    case 'object': return {};
    default: return undefined;
  }
}
