import { DRMErrorCode } from '../types/DRMTypes';
import { DRMErrorHandler } from './DRMErrorHandler';

export class CertificateManager {
  private cache = new Map<string, Uint8Array>();

  async fetchCertificate(url: string, headers?: Record<string, string>): Promise<Uint8Array> {
    const cached = this.cache.get(url);
    if (cached) return cached;

    try {
      const resp = await fetch(url, {
        method: 'GET',
        headers: headers || {},
      });
      if (!resp.ok) {
        throw DRMErrorHandler.createError(
          DRMErrorCode.CERTIFICATE_FETCH_FAILED,
          `Certificate fetch failed: HTTP ${resp.status}`,
        );
      }
      const buf = await resp.arrayBuffer();
      const cert = new Uint8Array(buf);
      this.cache.set(url, cert);
      return cert;
    } catch (error: any) {
      if (error.code === DRMErrorCode.CERTIFICATE_FETCH_FAILED) throw error;
      throw DRMErrorHandler.createError(
        DRMErrorCode.CERTIFICATE_FETCH_FAILED,
        `Certificate fetch failed: ${error.message}`,
        error,
      );
    }
  }

  clear(): void {
    this.cache.clear();
  }
}
