All files / src/components/features/admin/api-docs ApiTester.tsx

0% Statements 0/556
100% Branches 0/0
0% Functions 0/1
0% Lines 0/556

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         
'use client';

/**
 * API Tester Component
 * Interactive interface for testing API endpoints
 */

import React, { useState, useEffect } from 'react';
import { ApiEndpoint, ApiTestResponse } from '@/types/api-docs';
import {
  executeRequest,
  buildRequestUrl,
  getMethodColor,
  getStatusColor,
  getStatusBgColor,
  formatJson,
  generateCurl,
  generateTypescript,
  generateJavascript,
  generatePython,
  addToHistory,
  saveRequest,
  downloadOpenAPISpec,
  downloadOpenAPISpecYaml } from '@/lib/api-docs/executor';
import { Icon } from '@/components/ui/icons';
import ResponseValidation from './ResponseValidation';

interface ApiTesterProps {
  endpoint: ApiEndpoint;
  onClose?: () => void;
}

type CodeTab = 'response' | 'validation' | 'curl' | 'typescript' | 'javascript' | 'python';

export default function ApiTester({ endpoint, onClose }: ApiTesterProps) {
  // Path parameters
  const pathParams = endpoint.parameters?.filter((p) => p.location === 'path') || [];
  const queryParams = endpoint.parameters?.filter((p) => p.location === 'query') || [];

  // State
  const [pathValues, setPathValues] = useState<Record<string, string>>(() => {
    const initial: Record<string, string> = {};
    pathParams.forEach((p) => {
      initial[p.name] = p.example?.toString() || '';
    });
    return initial;
  });

  const [queryValues, setQueryValues] = useState<Record<string, string>>(() => {
    const initial: Record<string, string> = {};
    queryParams.forEach((p) => {
      initial[p.name] = '';
    });
    return initial;
  });

  // Headers editor not yet implemented
  const [headers] = useState<Record<string, string>>({});
  const [body, setBody] = useState<string>(
    endpoint.requestBody?.example ? JSON.stringify(endpoint.requestBody.example, null, 2) : ''
  );
  const [useAuth, setUseAuth] = useState(endpoint.requiresAuth);
  const [loading, setLoading] = useState(false);
  const [response, setResponse] = useState<ApiTestResponse | null>(null);
  const [codeTab, setCodeTab] = useState<CodeTab>('response');
  const [bodyError, setBodyError] = useState<string | null>(null);
  const [showSaveModal, setShowSaveModal] = useState(false);
  const [saveName, setSaveName] = useState('');
  const [saveSuccess, setSaveSuccess] = useState(false);

  // Build URL preview
  const urlPreview = buildRequestUrl(endpoint, pathValues, queryValues);

  // Validate JSON body
  useEffect(() => {
    if (!body.trim()) {
      setBodyError(null);
      return;
    }
    try {
      JSON.parse(body);
      setBodyError(null);
    } catch {
      setBodyError('Invalid JSON');
    }
  }, [body]);

  const handleExecute = async () => {
    let parsedBody = undefined;
    if (body.trim() && ['POST', 'PUT', 'PATCH'].includes(endpoint.method)) {
      try {
        parsedBody = JSON.parse(body);
      } catch {
        setBodyError('Invalid JSON - cannot execute request');
        return;
      }
    }

    setLoading(true);
    setResponse(null);

    const request = {
      endpoint,
      pathParams: pathValues,
      queryParams: queryValues,
      headers,
      body: parsedBody,
      useAuth};

    try {
      const result = await executeRequest(request);
      setResponse(result);
      addToHistory(request, result);
    } catch (error) {
      setResponse({
        status: 0,
        statusText: 'Error',
        headers: {},
        body: { error: error instanceof Error ? error.message : 'Unknown error' },
        duration: 0,
        timestamp: new Date()});
    } finally {
      setLoading(false);
    }
  };

  const currentRequest = {
    endpoint,
    pathParams: pathValues,
    queryParams: queryValues,
    headers,
    body: body ? JSON.parse(body || '{}') : undefined,
    useAuth};

  const handleSaveRequest = () => {
    if (!saveName.trim()) return;
    saveRequest(saveName, currentRequest);
    setSaveSuccess(true);
    setTimeout(() => {
      setShowSaveModal(false);
      setSaveName('');
      setSaveSuccess(false);
    }, 1500);
  };

  return (
    <div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 overflow-hidden">
      {/* Header */}
      <div className="p-4 border-b border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-700/50">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-3">
            <span
              className={`text-sm font-mono font-bold px-2 py-1 rounded ${getMethodColor(
                endpoint.method
              )}`}
            >
              {endpoint.method}
            </span>
            <span className="font-medium text-gray-900 dark:text-gray-100">{endpoint.summary}</span>
          </div>
          <div className="flex items-center gap-2">
            {/* Save Request Button */}
            <button
              onClick={() => setShowSaveModal(true)}
              className="text-gray-500 dark:text-gray-400 hover:text-indigo-600 dark:hover:text-indigo-400"
              title="Save request"
            >
              <Icon name="bookmark" size={20} />
            </button>
            {/* Export Menu */}
            <div className="relative group">
              <button
                className="text-gray-500 dark:text-gray-400 hover:text-indigo-600 dark:hover:text-indigo-400"
                title="Export OpenAPI spec"
              >
                <Icon name="file-download" size={20} />
              </button>
              <div className="absolute right-0 top-full mt-1 w-40 bg-white dark:bg-gray-800 rounded shadow-lg border border-gray-200 dark:border-gray-700 hidden group-hover:block z-10">
                <button
                  onClick={() => downloadOpenAPISpec()}
                  className="w-full px-3 py-2 text-left text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700"
                >
                  Export as JSON
                </button>
                <button
                  onClick={() => downloadOpenAPISpecYaml()}
                  className="w-full px-3 py-2 text-left text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700"
                >
                  Export as YAML
                </button>
              </div>
            </div>
            {onClose && (
              <button
                onClick={onClose}
                className="text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-200"
              >
                <Icon name="close" size={20} />
              </button>
            )}
          </div>
        </div>
        <div className="mt-2 flex items-center gap-2">
          <code className="text-sm text-gray-600 dark:text-gray-300 bg-white dark:bg-gray-800 px-2 py-1 rounded border border-gray-200 dark:border-gray-600 flex-1 overflow-x-auto">
            {urlPreview}
          </code>
          <button
            onClick={handleExecute}
            disabled={loading}
            className="px-4 py-1.5 bg-indigo-600 text-white rounded hover:bg-indigo-700 transition-colors disabled:opacity-50 flex items-center gap-2"
          >
            {loading ? (
              <>
                <Icon name="spinner" size={16} className="animate-spin" />
                Sending...
              </>
            ) : (
              <>
                <Icon name="bolt" size={16} />
                Send
              </>
            )}
          </button>
        </div>
      </div>

      <div className="flex divide-x divide-gray-200 dark:divide-gray-700">
        {/* Request Panel */}
        <div className="flex-1 p-4">
          <h3 className="font-medium text-gray-900 dark:text-gray-100 mb-4">Request</h3>

          {/* Auth Toggle */}
          <div className="mb-4">
            <label className="flex items-center gap-2 cursor-pointer">
              <input
                type="checkbox"
                checked={useAuth}
                onChange={(e) => setUseAuth(e.target.checked)}
                className="w-4 h-4 text-indigo-600 rounded border-gray-300 dark:border-gray-600 focus:ring-indigo-500 dark:bg-gray-700"
              />
              <span className="text-sm text-gray-700 dark:text-gray-300">Include authentication (cookies)</span>
            </label>
          </div>

          {/* Path Parameters */}
          {pathParams.length > 0 && (
            <div className="mb-4">
              <h4 className="text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Path Parameters</h4>
              <div className="space-y-2">
                {pathParams.map((param) => (
                  <div key={param.name} className="flex items-center gap-2">
                    <label className="w-32 text-sm text-gray-600 dark:text-gray-400 font-mono">
                      {param.name}
                      {param.required && <span className="text-red-500 dark:text-red-400">*</span>}
                    </label>
                    <input
                      type="text"
                      value={pathValues[param.name] || ''}
                      onChange={(e) =>
                        setPathValues((prev) => ({ ...prev, [param.name]: e.target.value }))
                      }
                      placeholder={param.example?.toString() || param.type}
                      className="flex-1 px-2 py-1 text-sm border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 rounded focus:outline-none focus:ring-1 focus:ring-indigo-500 placeholder-gray-400 dark:placeholder-gray-500"
                    />
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* Query Parameters */}
          {queryParams.length > 0 && (
            <div className="mb-4">
              <h4 className="text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Query Parameters</h4>
              <div className="space-y-2">
                {queryParams.map((param) => (
                  <div key={param.name} className="flex items-center gap-2">
                    <label className="w-32 text-sm text-gray-600 dark:text-gray-400 font-mono">
                      {param.name}
                      {param.required && <span className="text-red-500 dark:text-red-400">*</span>}
                    </label>
                    {param.enum ? (
                      <select
                        value={queryValues[param.name] || ''}
                        onChange={(e) =>
                          setQueryValues((prev) => ({ ...prev, [param.name]: e.target.value }))
                        }
                        className="flex-1 px-2 py-1 text-sm border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 rounded focus:outline-none focus:ring-1 focus:ring-indigo-500"
                      >
                        <option value="">Select...</option>
                        {param.enum.map((opt) => (
                          <option key={opt} value={opt}>
                            {opt}
                          </option>
                        ))}
                      </select>
                    ) : (
                      <input
                        type="text"
                        value={queryValues[param.name] || ''}
                        onChange={(e) =>
                          setQueryValues((prev) => ({ ...prev, [param.name]: e.target.value }))
                        }
                        placeholder={param.example?.toString() || param.type}
                        className="flex-1 px-2 py-1 text-sm border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 rounded focus:outline-none focus:ring-1 focus:ring-indigo-500 placeholder-gray-400 dark:placeholder-gray-500"
                      />
                    )}
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* Request Body */}
          {['POST', 'PUT', 'PATCH'].includes(endpoint.method) && (
            <div className="mb-4">
              <h4 className="text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                Request Body
                {bodyError && (
                  <span className="ml-2 text-red-500 dark:text-red-400 text-xs">{bodyError}</span>
                )}
              </h4>
              <textarea
                value={body}
                onChange={(e) => setBody(e.target.value)}
                rows={8}
                className={`w-full px-3 py-2 text-sm font-mono border rounded focus:outline-none focus:ring-1 focus:ring-indigo-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 ${
                  bodyError ? 'border-red-300 dark:border-red-500' : 'border-gray-300 dark:border-gray-600'
                }`}
                placeholder="{ }"
              />
            </div>
          )}
        </div>

        {/* Response Panel */}
        <div className="flex-1 p-4">
          {/* Tabs */}
          <div className="flex items-center gap-1 mb-4 border-b border-gray-200 dark:border-gray-700">
            <button
              onClick={() => setCodeTab('response')}
              className={`px-3 py-2 text-sm font-medium border-b-2 -mb-px transition-colors ${
                codeTab === 'response'
                  ? 'border-indigo-500 text-indigo-600 dark:text-indigo-400'
                  : 'border-transparent text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300'
              }`}
            >
              Response
            </button>
            <button
              onClick={() => setCodeTab('validation')}
              disabled={!response}
              className={`px-3 py-2 text-sm font-medium border-b-2 -mb-px transition-colors ${
                codeTab === 'validation'
                  ? 'border-indigo-500 text-indigo-600 dark:text-indigo-400'
                  : 'border-transparent text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300'
              } ${!response ? 'opacity-50 cursor-not-allowed' : ''}`}
            >
              Validation
            </button>
            <button
              onClick={() => setCodeTab('curl')}
              className={`px-3 py-2 text-sm font-medium border-b-2 -mb-px transition-colors ${
                codeTab === 'curl'
                  ? 'border-indigo-500 text-indigo-600 dark:text-indigo-400'
                  : 'border-transparent text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300'
              }`}
            >
              cURL
            </button>
            <button
              onClick={() => setCodeTab('typescript')}
              className={`px-3 py-2 text-sm font-medium border-b-2 -mb-px transition-colors ${
                codeTab === 'typescript'
                  ? 'border-indigo-500 text-indigo-600 dark:text-indigo-400'
                  : 'border-transparent text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300'
              }`}
            >
              TypeScript
            </button>
            <button
              onClick={() => setCodeTab('javascript')}
              className={`px-3 py-2 text-sm font-medium border-b-2 -mb-px transition-colors ${
                codeTab === 'javascript'
                  ? 'border-indigo-500 text-indigo-600 dark:text-indigo-400'
                  : 'border-transparent text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300'
              }`}
            >
              JavaScript
            </button>
            <button
              onClick={() => setCodeTab('python')}
              className={`px-3 py-2 text-sm font-medium border-b-2 -mb-px transition-colors ${
                codeTab === 'python'
                  ? 'border-indigo-500 text-indigo-600 dark:text-indigo-400'
                  : 'border-transparent text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300'
              }`}
            >
              Python
            </button>
          </div>

          {/* Tab Content */}
          {codeTab === 'response' && (
            <>
              {response ? (
                <div>
                  {/* Status */}
                  <div className="flex items-center gap-4 mb-4">
                    <span
                      className={`px-2 py-1 rounded font-mono font-bold ${getStatusBgColor(
                        response.status
                      )} ${getStatusColor(response.status)}`}
                    >
                      {response.status} {response.statusText}
                    </span>
                    <span className="text-sm text-gray-500 dark:text-gray-400">{response.duration}ms</span>
                  </div>

                  {/* Response Body */}
                  <pre className="bg-gray-900 text-gray-100 p-4 rounded-lg overflow-auto text-sm max-h-96">
                    {formatJson(response.body)}
                  </pre>
                </div>
              ) : (
                <div className="flex items-center justify-center h-48 text-gray-400 dark:text-gray-500">
                  <div className="text-center">
                    <Icon name="terminal" size={48} className="mx-auto mb-2 opacity-50" />
                    <p>Click Send to execute the request</p>
                  </div>
                </div>
              )}
            </>
          )}

          {codeTab === 'validation' && response && (
            <ResponseValidation
              endpoint={endpoint}
              status={response.status}
              responseBody={response.body}
            />
          )}

          {codeTab === 'curl' && (
            <div className="relative">
              <button
                onClick={() => navigator.clipboard.writeText(generateCurl(currentRequest))}
                className="absolute top-2 right-2 px-2 py-1 bg-gray-700 text-gray-300 text-xs rounded hover:bg-gray-600"
              >
                Copy
              </button>
              <pre className="bg-gray-900 text-gray-100 p-4 rounded-lg overflow-auto text-sm">
                {generateCurl(currentRequest)}
              </pre>
            </div>
          )}

          {codeTab === 'typescript' && (
            <div className="relative">
              <button
                onClick={() => navigator.clipboard.writeText(generateTypescript(currentRequest))}
                className="absolute top-2 right-2 px-2 py-1 bg-gray-700 text-gray-300 text-xs rounded hover:bg-gray-600"
              >
                Copy
              </button>
              <pre className="bg-gray-900 text-gray-100 p-4 rounded-lg overflow-auto text-sm">
                {generateTypescript(currentRequest)}
              </pre>
            </div>
          )}

          {codeTab === 'javascript' && (
            <div className="relative">
              <button
                onClick={() => navigator.clipboard.writeText(generateJavascript(currentRequest))}
                className="absolute top-2 right-2 px-2 py-1 bg-gray-700 text-gray-300 text-xs rounded hover:bg-gray-600"
              >
                Copy
              </button>
              <pre className="bg-gray-900 text-gray-100 p-4 rounded-lg overflow-auto text-sm">
                {generateJavascript(currentRequest)}
              </pre>
            </div>
          )}

          {codeTab === 'python' && (
            <div className="relative">
              <button
                onClick={() => navigator.clipboard.writeText(generatePython(currentRequest))}
                className="absolute top-2 right-2 px-2 py-1 bg-gray-700 text-gray-300 text-xs rounded hover:bg-gray-600"
              >
                Copy
              </button>
              <pre className="bg-gray-900 text-gray-100 p-4 rounded-lg overflow-auto text-sm">
                {generatePython(currentRequest)}
              </pre>
            </div>
          )}
        </div>
      </div>

      {/* Save Request Modal */}
      {showSaveModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl w-96 mx-4">
            <div className="p-4 border-b border-gray-200 dark:border-gray-700">
              <h3 className="font-semibold text-gray-900 dark:text-gray-100">Save Request</h3>
            </div>
            <div className="p-4">
              {saveSuccess ? (
                <div className="flex items-center justify-center gap-2 text-green-600 dark:text-green-400 py-4">
                  <Icon name="check" size={24} />
                  <span>Request saved!</span>
                </div>
              ) : (
                <>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    Request Name
                  </label>
                  <input
                    type="text"
                    value={saveName}
                    onChange={(e) => setSaveName(e.target.value)}
                    placeholder={`${endpoint.method} ${endpoint.summary}`}
                    className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-indigo-500"
                    autoFocus
                  />
                </>
              )}
            </div>
            {!saveSuccess && (
              <div className="p-4 border-t border-gray-200 dark:border-gray-700 flex justify-end gap-2">
                <button
                  onClick={() => {
                    setShowSaveModal(false);
                    setSaveName('');
                  }}
                  className="px-4 py-2 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded transition-colors"
                >
                  Cancel
                </button>
                <button
                  onClick={handleSaveRequest}
                  disabled={!saveName.trim()}
                  className="px-4 py-2 text-sm bg-indigo-600 text-white rounded hover:bg-indigo-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                >
                  Save
                </button>
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  );
}