const SUPPORTED_CONTENT_TYPES = ['text', 'image', 'video', 'audio', 'other'];

export function resolveWorkflowFormParameters(workflowParams: any) {
  const schema = Array.isArray(workflowParams?.startFormSchema)
    ? workflowParams.startFormSchema
    : [];
  if (schema.length === 0) {
    return workflowParams?.parameters || [];
  }
  const parameterMap = new Map(
    (Array.isArray(workflowParams?.parameters)
      ? workflowParams.parameters
      : []
    ).map((parameter: any) => [
      String(parameter?.name || '').trim(),
      parameter,
    ]),
  );
  return schema.map((field: any) => {
    const type = String(field.type || '').trim() || 'text';
    const rawContentType = String(field.contentType || '').trim();
    const parameter = parameterMap.get(String(field.key || '').trim()) as
      | any
      | undefined;
    const parameterContentType = String(parameter?.contentType || '').trim();
    const contentType =
      type === 'file'
        ? 'file'
        : parameterContentType === 'image'
          ? 'image'
          : SUPPORTED_CONTENT_TYPES.includes(rawContentType)
            ? rawContentType
            : 'text';
    return {
      name: field.key,
      formLabel: field.label || field.key,
      formDescription: field.description || '',
      formPlaceholder: field.placeholder || '',
      required: Boolean(field.required),
      defaultValue: field.defaultValue,
      enums: Array.isArray(field.options) ? field.options : [],
      contentType,
      formType: type === 'text' || contentType === 'file' ? 'input' : type,
      dataType:
        type === 'checkbox'
          ? 'Array'
          : contentType === 'file'
            ? 'File'
            : contentType === 'image'
              ? 'Object'
              : 'String',
    };
  });
}
