import { Context, Next } from 'koa';

export async function errorHandler(ctx: Context, next: Next): Promise<void> {
  try {
    await next();
  } catch (err: unknown) {
    const error = err as Error & { status?: number; code?: number };
    
    console.error('❌ Error:', error.message);
    console.error('Stack:', error.stack);

    ctx.status = error.status || 500;
    ctx.body = {
      code: error.code || 500,
      message: error.message || '服务器内部错误',
      data: null,
    };

    // 开发环境返回详细错误
    if (process.env.NODE_ENV === 'development') {
      (ctx.body as Record<string, unknown>).stack = error.stack;
    }
  }
}

// 自定义错误类
export class AppError extends Error {
  public code: number;
  public status: number;

  constructor(message: string, code: number = 500, status: number = 500) {
    super(message);
    this.code = code;
    this.status = status;
    this.name = 'AppError';
  }
}

export class UnauthorizedError extends AppError {
  constructor(message: string = '未授权访问') {
    super(message, 401, 401);
  }
}

export class ForbiddenError extends AppError {
  constructor(message: string = '禁止访问') {
    super(message, 403, 403);
  }
}

export class NotFoundError extends AppError {
  constructor(message: string = '资源不存在') {
    super(message, 404, 404);
  }
}

export class BadRequestError extends AppError {
  constructor(message: string = '请求参数错误') {
    super(message, 400, 400);
  }
}

export class QuotaExceededError extends AppError {
  constructor(message: string = '使用次数已达上限') {
    super(message, 429, 429);
  }
}