/**
 * GeneratedMediaResolverAdapter
 * 
 * Resolves generated media references to image serving URLs.
 * Part of the adapters layer, implementing the MediaResolverPort interface.
 */

import { MediaReference } from '@core/domain/media/MediaReference';
import { MediaResolverPort } from '@core/ports/media/MediaResolverPort';

/**
 * Configuration for the GeneratedMediaResolverAdapter
 */
export interface GeneratedMediaResolverConfig {
  /**
   * Base path for generated assets (defaults to '/media/generated')
   * @deprecated No longer used - returns path-only URLs
   */
  basePath?: string | undefined;
}

/**
 * GeneratedMediaResolverAdapter
 * 
 * Resolves generated media references to image serving URLs.
 * 
 * URL format: /media/generated/{type}/{id}
 * Examples:
 * - /media/teams/{id}/logo
 * - /media/leagues/{id}/logo
 * - /media/avatar/{id}
 * 
 * The type and id are extracted from the generationRequestId.
 * Format: "{type}-{id}" (e.g., "team-123", "league-456")
 */
export class GeneratedMediaResolverAdapter implements MediaResolverPort {
  constructor(_config: GeneratedMediaResolverConfig = {}) {
    // basePath is not used since we return path-only URLs
    // config.basePath is ignored for backward compatibility
  }

  /**
   * Resolve a generated media reference to a path-only URL
   * Returns paths like /media/teams/{id}/logo (no baseUrl)
   */
  async resolve(ref: MediaReference): Promise<string | null> {
    // Only handle generated references
    if (ref.type !== 'generated') {
      return null;
    }

    // Parse the generationRequestId to extract type and id
    // Format: "{type}-{id}" or "{type}-{subtype}-{id}"
    const requestId = ref.generationRequestId;
    
    if (!requestId) {
      return null;
    }
    
    // Find the first hyphen to split type and id
    // Format: "{type}-{id}" where id can contain hyphens
    const firstHyphenIndex = requestId.indexOf('-');
    if (firstHyphenIndex === -1) {
      // Invalid format
      return null;
    }

    const type = requestId.substring(0, firstHyphenIndex);
    const id = requestId.substring(firstHyphenIndex + 1);

    // Return path-only URLs matching the API routes
    if (type === 'team') {
      return `/media/teams/${id}/logo`;
    } else if (type === 'league') {
      return `/media/leagues/${id}/logo`;
    } else if (type === 'driver') {
      return `/media/avatar/${id}`;
    }
    
    // Fallback for other types
    return `/media/generated/${type}/${id}`;
  }
}

/**
 * Factory function for creating GeneratedMediaResolverAdapter instances
 */
export function createGeneratedMediaResolver(
  config: GeneratedMediaResolverConfig = {}
): GeneratedMediaResolverAdapter {
  return new GeneratedMediaResolverAdapter(config);
}