/**
 * Action抽象基类
 */

import { IAction, IActionContext } from '../interfaces/IAction';
import { IActionConfig, IActionResult } from '../types';

export abstract class BaseAction<TConfig extends IActionConfig = IActionConfig> 
  implements IAction {
  
  protected config: TConfig;
  protected context: IActionContext;
  private startTime: number = 0;

  constructor(config: TConfig, context: IActionContext) {
    this.config = config;
    this.context = context;
  }

  // 抽象方法 - 子类必须实现
  abstract execute(): Promise<IActionResult>;

  // 通用方法
  async validate(): Promise<boolean> {
    return true;
  }

  log(level: string, message: string): void {
    if (this.context.logger) {
      this.context.logger.log(level, message);
    } else {
      console.log(`[${level}] ${message}`);
    }
  }

  protected startTimer(): void {
    this.startTime = Date.now();
  }

  protected getDuration(): number {
    return Date.now() - this.startTime;
  }

  protected async delay(ms: number): Promise<void> {
    return new Promise(resolve => setTimeout(resolve, ms));
  }

  protected async retry<T>(
    fn: () => Promise<T>,
    maxRetries: number = 3,
    delayMs: number = 1000
  ): Promise<T> {
    let lastError: Error | undefined;
    
    for (let i = 0; i < maxRetries; i++) {
      try {
        return await fn();
      } catch (error) {
        lastError = error as Error;
        if (i < maxRetries - 1) {
          await this.delay(delayMs * (i + 1));
        }
      }
    }
    
    throw lastError;
  }
}
