import { BaseDRM } from './BaseDRM';
import { KEY_SYSTEMS, DRMInitResult, DRMErrorCode } from '../types/DRMTypes';
import { DRMErrorHandler } from '../utils/DRMErrorHandler';
import { CertificateManager } from '../utils/CertificateManager';

export class FairPlayDRM extends BaseDRM {
  private certManager = new CertificateManager();

  getKeySystem(): string { return KEY_SYSTEMS.FAIRPLAY; }

  async initialize(): Promise<DRMInitResult> {
    try {
      if (!this.config.certificateUrl) {
        return {
          success: false,
          error: DRMErrorHandler.createError(DRMErrorCode.CERTIFICATE_FETCH_FAILED, 'FairPlay requires certificateUrl'),
        };
      }
      const cert = await this.certManager.fetchCertificate(this.config.certificateUrl, this.config.headers);
      this.log('FairPlay certificate fetched, size:', cert.byteLength);
      return { success: true, drmType: 'fairplay', keySystem: KEY_SYSTEMS.FAIRPLAY };
    } catch (error: any) {
      return {
        success: false,
        error: DRMErrorHandler.createError(DRMErrorCode.INITIALIZATION_FAILED, `FairPlay init failed: ${error.message}`, error),
      };
    }
  }

  getHLSConfig(): Record<string, any> {
    return {
      emeEnabled: true,
      drmSystems: {
        'com.apple.fps.1_0': {
          licenseUrl: this.config.licenseUrl,
          serverCertificateUrl: this.config.certificateUrl,
        },
      },
    };
  }

  async destroy(): Promise<void> {
    this.certManager.clear();
    this.log('FairPlay DRM destroyed');
  }
}
