import { BaseDRM } from './BaseDRM';
import { KEY_SYSTEMS, DRMInitResult, DRMErrorCode } from '../types/DRMTypes';
import { DRMErrorHandler } from '../utils/DRMErrorHandler';

export class PlayReadyDRM extends BaseDRM {
  getKeySystem(): string { return KEY_SYSTEMS.PLAYREADY; }

  async initialize(): Promise<DRMInitResult> {
    try {
      const config: MediaKeySystemConfiguration[] = [{
        initDataTypes: ['cenc'],
        videoCapabilities: [{ contentType: 'video/mp4; codecs="avc1.42E01E"' }],
        audioCapabilities: [{ contentType: 'audio/mp4; codecs="mp4a.40.2"' }],
        persistentState: this.config.persistentState || 'optional',
        distinctiveIdentifier: this.config.distinctiveIdentifier || 'optional',
      }];

      await navigator.requestMediaKeySystemAccess(KEY_SYSTEMS.PLAYREADY, config);
      this.log('PlayReady access granted');
      return { success: true, drmType: 'playready', keySystem: KEY_SYSTEMS.PLAYREADY };
    } catch (error: any) {
      return {
        success: false,
        error: DRMErrorHandler.createError(DRMErrorCode.INITIALIZATION_FAILED, `PlayReady init failed: ${error.message}`, error),
      };
    }
  }

  getDashProtectionData(): Record<string, any> {
    return {
      [KEY_SYSTEMS.PLAYREADY]: {
        serverURL: this.config.licenseUrl,
        httpRequestHeaders: this.config.headers || {},
        withCredentials: this.config.withCredentials || false,
      },
    };
  }

  async destroy(): Promise<void> {
    this.log('PlayReady DRM destroyed');
  }
}
