/**
 * {{ operation.summary or 'API operation' }}
 *
 * @method {{ operation.http_method }}
 * @path {{ operation.path }}
 */
export async function {{ func_name }}(
{%- if func_params %}
  {{ func_params }},
{%- endif %}
  client?: any
): Promise<{{ response_type }}> {
  const api = client || getAPIInstance()
{% if api_call_params %}
  const response = await {{ api_call }}({{ api_call_params }})
{% else %}
  const response = await {{ api_call }}()
{% endif %}
{% if multi_response_schemas %}
  // Multi-response endpoint — try each schema
{% for schema in multi_response_schemas %}
  try {
    return {{ schema.schema }}.parse(response) as {{ response_type }}
  } catch { /* try next schema */ }
{% endfor %}

  // None matched — log and return raw response
  consola.warn('{{ func_name }}: response did not match any expected schema')
  consola.warn('Response data:', response)
  return response as {{ response_type }}
{% elif response_schema %}
  try {
    return {{ response_validation }}.parse(response)
  } catch (error) {
    // Zod validation error - log detailed information
    consola.error('❌ Zod Validation Failed');
    consola.box(`{{ func_name }}\nPath: {{ operation.path }}\nMethod: {{ operation.http_method }}`);

    if (error instanceof Error && 'issues' in error && Array.isArray((error as any).issues)) {
      consola.error('Validation Issues:');
      (error as any).issues.forEach((issue: any, index: number) => {
        consola.error(`  ${index + 1}. ${issue.path.join('.') || 'root'}`);
        consola.error(`     ├─ Message: ${issue.message}`);
        if (issue.expected) consola.error(`     ├─ Expected: ${issue.expected}`);
        if (issue.received) consola.error(`     └─ Received: ${issue.received}`);
      });
    }

    consola.error('Response data:', response);

    // Dispatch browser CustomEvent (only if window is defined)
    if (typeof window !== 'undefined' && error instanceof Error && 'issues' in error) {
      try {
        const event = new CustomEvent('zod-validation-error', {
          detail: {
            operation: '{{ func_name }}',
            path: '{{ operation.path }}',
            method: '{{ operation.http_method }}',
            error: error,
            response: response,
            timestamp: new Date(),
          },
          bubbles: true,
          cancelable: false,
        });
        window.dispatchEvent(event);
      } catch (eventError) {
        // Silently fail - event dispatch should never crash the app
        consola.warn('Failed to dispatch validation error event:', eventError);
      }
    }

    // Re-throw the error
    throw error;
  }
{% else %}
  return response
{% endif %}
}

