import { Form, Input } from 'antd';
import { SchemaFields } from './SchemaFields';
import { resolveSchema, schemaType } from '../api/schema-utils';
import type { JsonSchema, OperationInput, PlatformOperation } from '../api/types';

function parseJsonFields(target: Record<string, unknown>, schema: JsonSchema) {
  const resolved = resolveSchema(schema);
  for (const [name, propertySchema] of Object.entries(resolved.properties || {})) {
    const value = target[name];
    const type = schemaType(propertySchema);
    if ((type === 'object' || type === 'array') && typeof value === 'string' && value.trim()) {
      try {
        target[name] = JSON.parse(value);
      } catch {
        throw new Error(`${propertySchema.description || name} 必须是有效 JSON`);
      }
    }
  }
}

export function normalizeOperationInput(operation: PlatformOperation, values: OperationInput): OperationInput {
  const input = structuredClone(values);
  if (input.body && typeof input.body === 'object' && operation.requestSchema) {
    parseJsonFields(input.body as Record<string, unknown>, operation.requestSchema);
  }
  return input;
}

export function OperationForm({ operation }: { operation: PlatformOperation }) {
  const pathParameters = operation.parameters.filter((item) => item.in === 'path');
  const queryParameters = operation.parameters.filter((item) => item.in === 'query');
  const headerParameters = operation.parameters.filter((item) => item.in === 'header');
  const bodySchema = resolveSchema(operation.requestSchema);
  return (
    <>
      {pathParameters.map((parameter) => (
        <Form.Item
          key={`path-${parameter.name}`}
          name={['path', parameter.name]}
          label={parameter.description || parameter.name}
          rules={[{ required: true, message: `请填写${parameter.description || parameter.name}` }]}
          tooltip={`路径参数：${parameter.name}`}
        >
          <Input />
        </Form.Item>
      ))}
      {queryParameters.length > 0 && (
        <SchemaFields
          prefix="query"
          required={queryParameters.filter((item) => item.required).map((item) => item.name)}
          schema={{
            type: 'object',
            properties: Object.fromEntries(queryParameters.map((item) => [item.name, { ...item.schema, description: item.description || item.name }])),
          }}
        />
      )}
      {headerParameters.map((parameter) => (
        <Form.Item
          key={`header-${parameter.name}`}
          name={['headers', parameter.name]}
          label={parameter.description || parameter.name}
          rules={[{ required: parameter.required, message: `请填写${parameter.description || parameter.name}` }]}
          initialValue={parameter.name.toLowerCase() === 'idempotency-key' ? crypto.randomUUID() : undefined}
        >
          <Input />
        </Form.Item>
      ))}
      {operation.requestSchema && schemaType(bodySchema) === 'object' && (
        <SchemaFields schema={bodySchema} prefix="body" required={bodySchema.required} />
      )}
    </>
  );
}
