/**
 * DefaultMediaResolverAdapter
 * 
 * Resolves system-default media references to public asset 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 DefaultMediaResolverAdapter
 */
export interface DefaultMediaResolverConfig {
  /**
   * Base path for default assets (defaults to '/media/default')
   */
  basePath?: string | undefined;
}

/**
 * DefaultMediaResolverAdapter
 * 
 * Resolves system-default media references to public asset URLs.
 * 
 * URL format: /media/default/{variant}
 * Examples:
 * - /media/default/male-default-avatar
 * - /media/default/female-default-avatar
 * - /media/default/neutral-default-avatar
 * - /media/default/team-logo.png
 * - /media/default/league-logo.png
 */
export class DefaultMediaResolverAdapter implements MediaResolverPort {
  private readonly basePath: string;

  constructor(config: DefaultMediaResolverConfig = {}) {
    this.basePath = config.basePath || '/media/default';
  }

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

    // Determine the filename based on variant and avatarVariant
    let filename: string;
    
    if (ref.variant === 'avatar' && ref.avatarVariant) {
      // Driver avatars must use website public assets:
      // apps/website/public/images/avatars/{male|female|neutral}-default-avatar.(jpg|jpeg)
      // We intentionally keep the URL extension-less; MediaController maps it to the real file.
      filename = `${ref.avatarVariant}-default-avatar`;
    } else if (ref.variant === 'avatar') {
      // Avatar without specific variant (fallback to neutral)
      filename = `neutral-default-avatar`;
    } else {
      // Other variants (team, league, etc.)
      filename = `${ref.variant}.png`;
    }

    // Return path-only URL
    return `${this.basePath}/${filename}`;
  }
}

/**
 * Factory function for creating DefaultMediaResolverAdapter instances
 */
export function createDefaultMediaResolver(
  config: DefaultMediaResolverConfig = {}
): DefaultMediaResolverAdapter {
  return new DefaultMediaResolverAdapter(config);
}
