import { useEffect, useRef } from 'react';
import { useAuthStore } from '../../auth/auth-store';
import SwaggerUI from 'swagger-ui-dist/swagger-ui-es-bundle.js';
import 'swagger-ui-dist/swagger-ui.css';
import styles from './SwaggerPage.module.css';

export function SwaggerPage() {
  const containerRef = useRef<HTMLDivElement>(null);
  const token = useAuthStore((s) => s.accessToken);

  useEffect(() => {
    if (!containerRef.current) return;
    containerRef.current.innerHTML = '';

    SwaggerUI({
      url: '/api/v1/api-docs',
      domNode: containerRef.current,
      deepLinking: true,
      requestInterceptor: (req: Record<string, unknown>) => {
        if (token) {
          (req.headers as Record<string, string>)['Authorization'] = `Bearer ${token}`;
        }
        return req;
      },
    });
  }, [token]);

  return <div ref={containerRef} className={styles.container} />;
}
