import type { EngineErrorShape } from './ffmpeg.types';

export class EngineError extends Error implements EngineErrorShape {
  readonly code: EngineErrorShape['code'];
  readonly details?: string;
  readonly exitCode?: number;

  constructor(
    code: EngineErrorShape['code'],
    message: string,
    options: {
      cause?: unknown;
      details?: string;
      exitCode?: number;
    } = {}
  ) {
    super(message, { cause: options.cause });
    this.name = 'EngineError';
    this.code = code;
    this.details = options.details;
    this.exitCode = options.exitCode;
  }
}

export function toEngineError(error: unknown): EngineError {
  if (error instanceof EngineError) {
    return error;
  }
  if (error instanceof Error) {
    return new EngineError('execution-failed', error.message, {
      cause: error,
      details: error.stack,
    });
  }
  return new EngineError('execution-failed', 'Unknown FFmpeg error', {
    details: String(error),
  });
}
