/**
 * Centralized API configuration for the CodeNuk frontend
 * All API base URLs are managed from this single location
 */

// Default API base URL - can be overridden by environment variables
const DEFAULT_API_BASE_URL = 'http://localhost:8000';

// Environment-based configuration
export const API_CONFIG = {
  // Main API base URL
  BASE_URL: process.env.NEXT_PUBLIC_API_URL || DEFAULT_API_BASE_URL,
  
  // Specific service endpoints (if needed in the future)
  AUTH_SERVICE: process.env.NEXT_PUBLIC_AUTH_API_URL || DEFAULT_API_BASE_URL,
  TEMPLATE_SERVICE: process.env.NEXT_PUBLIC_TEMPLATE_MANAGER_URL || DEFAULT_API_BASE_URL,
  GENERATION_SERVICE: process.env.NEXT_PUBLIC_GENERATION_SERVICE_URL || DEFAULT_API_BASE_URL,
  SELECTION_SERVICE: process.env.NEXT_PUBLIC_SELECTION_SERVICE_URL || DEFAULT_API_BASE_URL,
  
  // AI Mockup Wireframe Service via API Gateway
  // Route through gateway on port 8000 to unify CORS/auth and service access
  AI_MOCKUP_SERVICE: process.env.NEXT_PUBLIC_BACKEND_URL || 'http://localhost:8000/api/mockup',
  USER_AUTH_SERVICE: process.env.NEXT_PUBLIC_AUTH_URL || 'http://localhost:8000/api/auth',
} as const;

// AI Mockup Configuration
export const AI_MOCKUP_CONFIG = {
  // Backend API configuration
  backend: {
    baseUrl: API_CONFIG.AI_MOCKUP_SERVICE,
    endpoints: {
      health: '/health',
      generateWireframe: '/generate-wireframe',
      generateWireframeDesktop: '/generate-wireframe/desktop',
      generateWireframeTablet: '/generate-wireframe/tablet',
      generateWireframeMobile: '/generate-wireframe/mobile',
      generateAllDevices: '/generate-all-devices',
      wireframes: '/api/wireframes',
      wireframe: (id?: string) => id ? `/api/wireframes/${id}` : '/api/wireframes',
    },
    timeout: 30000, // 30 seconds
  },
  
  // User Authentication Service
  auth: {
    baseUrl: API_CONFIG.USER_AUTH_SERVICE,
    endpoints: {
      health: '/health',
      register: '/api/auth/register',
      login: '/api/auth/login',
      logout: '/api/auth/logout',
      refresh: '/api/auth/refresh',
      profile: '/api/auth/me',
      preferences: '/api/auth/preferences',
      projects: '/api/auth/projects',
    },
    tokenKey: 'auth_token',
    refreshTokenKey: 'refresh_token',
  },
  
  // UI configuration
  ui: {
    maxPromptLength: 1000,
    statusCheckInterval: 10000, // 10 seconds
    generationTimeout: 30000, // 30 seconds
  },
  
  // Wireframe defaults
  wireframe: {
    defaultPageSize: { width: 1200, height: 800 },
    defaultSpacing: { gap: 16, padding: 20 },
    minElementSize: { width: 80, height: 40 },
  },
} as const;

// Export the main API base URL for backward compatibility
export const API_BASE_URL = API_CONFIG.BASE_URL;

// Temporary debug logging
console.log('🔧 API Config Debug:', {
  'process.env.NEXT_PUBLIC_API_URL': process.env.NEXT_PUBLIC_API_URL,
  'process.env.NEXT_PUBLIC_AUTH_API_URL': process.env.NEXT_PUBLIC_AUTH_API_URL,
  'DEFAULT_API_BASE_URL': DEFAULT_API_BASE_URL,
  'API_CONFIG.BASE_URL': API_CONFIG.BASE_URL,
  'API_CONFIG.AUTH_SERVICE': API_CONFIG.AUTH_SERVICE,
  'API_BASE_URL': API_BASE_URL
});

// Helper function to get full API endpoint URL
export const getApiUrl = (endpoint: string): string => {
  // Remove leading slash if present to avoid double slashes
  const cleanEndpoint = endpoint.startsWith('/') ? endpoint.slice(1) : endpoint;
  return `${API_CONFIG.BASE_URL}/${cleanEndpoint}`;
};

// Helper function to get service-specific URL
export const getServiceUrl = (service: keyof typeof API_CONFIG, endpoint: string): string => {
  const baseUrl = API_CONFIG[service];
  const cleanEndpoint = endpoint.startsWith('/') ? endpoint.slice(1) : endpoint;
  return `${baseUrl}/${cleanEndpoint}`;
};

// AI Mockup Helper Functions
export const getAIMockupApiUrl = (endpoint: string): string => {
  return `${AI_MOCKUP_CONFIG.backend.baseUrl}${endpoint}`;
};

export const getAIMockupAuthUrl = (endpoint: string): string => {
  return `${AI_MOCKUP_CONFIG.auth.baseUrl}${endpoint}`;
};

// Helper function to get health check URL
export const getAIMockupHealthUrl = (): string => {
  return getAIMockupApiUrl(AI_MOCKUP_CONFIG.backend.endpoints.health);
};

// Helper function to get auth health check URL
export const getAIMockupAuthHealthUrl = (): string => {
  return getAIMockupAuthUrl(AI_MOCKUP_CONFIG.auth.endpoints.health);
};

// Helper function to get wireframe generation URL for specific device
export const getWireframeGenerationUrl = (device: 'desktop' | 'tablet' | 'mobile' = 'desktop'): string => {
  switch (device) {
    case 'tablet':
      return getAIMockupApiUrl(AI_MOCKUP_CONFIG.backend.endpoints.generateWireframeTablet);
    case 'mobile':
      return getAIMockupApiUrl(AI_MOCKUP_CONFIG.backend.endpoints.generateWireframeMobile);
    case 'desktop':
    default:
      return getAIMockupApiUrl(AI_MOCKUP_CONFIG.backend.endpoints.generateWireframeDesktop);
  }
};

// Helper function to get universal wireframe generation URL (backward compatibility)
export const getUniversalWireframeGenerationUrl = (): string => {
  return getAIMockupApiUrl(AI_MOCKUP_CONFIG.backend.endpoints.generateWireframe);
};

// Helper function to get all devices generation URL
export const getAllDevicesGenerationUrl = (): string => {
  return getAIMockupApiUrl(AI_MOCKUP_CONFIG.backend.endpoints.generateAllDevices);
};

// Helper function to get wireframe persistence URLs
export const getWireframeUrl = (id?: string): string => {
  if (id) {
    return getAIMockupApiUrl(AI_MOCKUP_CONFIG.backend.endpoints.wireframe(id));
  }
  return getAIMockupApiUrl(AI_MOCKUP_CONFIG.backend.endpoints.wireframes);
};

// Helper function to get wireframe by ID URL
export const getWireframeByIdUrl = (id: string): string => {
  return getAIMockupApiUrl(AI_MOCKUP_CONFIG.backend.endpoints.wireframe(id));
};

// Authentication helper functions - Use consistent token retrieval
export const getAIMockupAuthHeaders = (): HeadersInit => {
  // Use the main auth system's token instead of separate token
  const token = typeof window !== 'undefined' ? localStorage.getItem('accessToken') : null;
  return token ? { 'Authorization': `Bearer ${token}` } : {};
};

export const getAIMockupAuthHeadersWithContentType = (): HeadersInit => {
  // Use the main auth system's token instead of separate token
  const token = typeof window !== 'undefined' ? localStorage.getItem('accessToken') : null;
  return {
    'Content-Type': 'application/json',
    ...(token ? { 'Authorization': `Bearer ${token}` } : {})
  };
};

export const isAIMockupAuthenticated = (): boolean => {
  // Use the main auth system's token instead of separate token
  const token = typeof window !== 'undefined' ? localStorage.getItem('accessToken') : null;
  return !!token;
};

export const getCurrentAIMockupUser = (): any => {
  try {
    // Use the main auth system's token instead of separate token
    const token = typeof window !== 'undefined' ? localStorage.getItem('accessToken') : null;
    if (!token) return null;
    
    // Decode JWT token to get user info
    const payload = JSON.parse(atob(token.split('.')[1]));
    return payload;
  } catch {
    return null;
  }
};
