/**
 * 表单管理模块业务异常
 * 
 * 遵循 API 规范中定义的错误码
 */

import { HttpStatus } from '@nestjs/common';
import { BusinessException } from '@common/exceptions/business.exception';

// ==================== 区域相关异常 ====================

/**
 * 缺少区域 ID 异常
 */
export class RegionRequiredException extends BusinessException {
  constructor() {
    super(
      '缺少区域标识（X-Region-Id 请求头）',
      'REGION_REQUIRED',
      HttpStatus.BAD_REQUEST,
    );
  }
}

/**
 * 无效区域 ID 异常
 */
export class InvalidRegionException extends BusinessException {
  constructor(regionId: string) {
    super(
      `无效的区域标识: ${regionId}，仅支持 CN / US / ME`,
      'INVALID_REGION',
      HttpStatus.BAD_REQUEST,
      { regionId, supportedRegions: ['CN', 'US', 'ME'] },
    );
  }
}

/**
 * 区域不匹配异常
 */
export class RegionMismatchException extends BusinessException {
  constructor(requestedRegion: string, resourceRegion: string) {
    super(
      `请求的区域 ${requestedRegion} 与资源所属区域 ${resourceRegion} 不一致`,
      'REGION_MISMATCH',
      HttpStatus.FORBIDDEN,
      { requestedRegion, resourceRegion },
    );
  }
}

/**
 * 跨区域操作被禁止异常
 */
export class CrossRegionForbiddenException extends BusinessException {
  constructor() {
    super(
      '跨区域操作需要 form:admin 权限',
      'CROSS_REGION_FORBIDDEN',
      HttpStatus.FORBIDDEN,
    );
  }
}

// ==================== 表单定义相关异常 ====================

/**
 * 表单定义不存在异常
 */
export class FormNotFoundException extends BusinessException {
  constructor(formId: string, regionId?: string) {
    super(
      regionId
        ? `表单定义 ${formId} 在区域 ${regionId} 中不存在`
        : `表单定义 ${formId} 不存在`,
      'FORM_NOT_FOUND',
      HttpStatus.NOT_FOUND,
      { formId, regionId },
    );
  }
}

/**
 * 表单已禁用异常
 */
export class FormDefinitionDisabledException extends BusinessException {
  constructor(formId: string) {
    super(
      `表单 ${formId} 已禁用，不允许新发起`,
      'FORM_DEFINITION_DISABLED',
      HttpStatus.FORBIDDEN,
      { formId },
    );
  }
}

/**
 * 表单已归档异常
 */
export class FormDefinitionArchivedException extends BusinessException {
  constructor(formId: string) {
    super(
      `表单 ${formId} 已归档，不允许任何操作`,
      'FORM_DEFINITION_ARCHIVED',
      HttpStatus.FORBIDDEN,
      { formId },
    );
  }
}

// ==================== 版本相关异常 ====================

/**
 * 版本不存在异常
 */
export class VersionNotFoundException extends BusinessException {
  constructor(version: number, formId?: string) {
    super(
      formId
        ? `表单 ${formId} 的版本 ${version} 不存在`
        : `版本 ${version} 不存在`,
      'VERSION_NOT_FOUND',
      HttpStatus.NOT_FOUND,
      { version, formId },
    );
  }
}

/**
 * 版本范围无效异常
 */
export class InvalidVersionRangeException extends BusinessException {
  constructor(from: number, to: number) {
    super(
      `版本范围无效: from (${from}) 必须小于 to (${to})`,
      'INVALID_VERSION_RANGE',
      HttpStatus.BAD_REQUEST,
      { from, to },
    );
  }
}

// ==================== 快照相关异常 ====================

/**
 * 快照不存在异常
 */
export class SnapshotNotFoundException extends BusinessException {
  constructor(snapshotId: string, regionId?: string) {
    super(
      regionId
        ? `快照 ${snapshotId} 在区域 ${regionId} 中不存在`
        : `快照 ${snapshotId} 不存在`,
      'SNAPSHOT_NOT_FOUND',
      HttpStatus.NOT_FOUND,
      { snapshotId, regionId },
    );
  }
}

/**
 * 没有激活快照异常
 */
export class NoActiveSnapshotException extends BusinessException {
  constructor(formId: string, regionId?: string) {
    super(
      regionId
        ? `表单 ${formId} 在区域 ${regionId} 没有已发布的版本`
        : `表单 ${formId} 没有已发布的版本`,
      'NO_ACTIVE_SNAPSHOT',
      HttpStatus.NOT_FOUND,
      { formId, regionId },
    );
  }
}

/**
 * 草稿已存在异常
 */
export class DraftAlreadyExistsException extends BusinessException {
  constructor(formId: string) {
    super(
      `表单 ${formId} 已有草稿版本，请先处理现有草稿`,
      'DRAFT_ALREADY_EXISTS',
      HttpStatus.CONFLICT,
      { formId },
    );
  }
}

/**
 * 待审核已存在异常
 */
export class PendingAlreadyExistsException extends BusinessException {
  constructor(formId: string) {
    super(
      `表单 ${formId} 已有待审核版本`,
      'PENDING_ALREADY_EXISTS',
      HttpStatus.CONFLICT,
      { formId },
    );
  }
}

/**
 * 快照已发布异常
 */
export class AlreadyPublishedException extends BusinessException {
  constructor(snapshotId: string) {
    super(
      `快照 ${snapshotId} 已发布`,
      'ALREADY_PUBLISHED',
      HttpStatus.CONFLICT,
      { snapshotId },
    );
  }
}

// ==================== 状态转换相关异常 ====================

/**
 * 状态转换无效异常
 */
export class InvalidStatusTransitionException extends BusinessException {
  constructor(currentStatus: string, targetStatus: string, context?: string) {
    super(
      context
        ? `无法从 ${currentStatus} 转换到 ${targetStatus}: ${context}`
        : `无法从 ${currentStatus} 转换到 ${targetStatus}`,
      'INVALID_STATUS_TRANSITION',
      HttpStatus.BAD_REQUEST,
      { currentStatus, targetStatus },
    );
  }
}

/**
 * 需要审核异常
 */
export class ReviewRequiredException extends BusinessException {
  constructor(snapshotId: string) {
    super(
      `快照 ${snapshotId} 需要先通过审核才能发布`,
      'REVIEW_REQUIRED',
      HttpStatus.BAD_REQUEST,
      { snapshotId },
    );
  }
}

// ==================== 实例相关异常 ====================

/**
 * 实例不存在异常
 */
export class InstanceNotFoundException extends BusinessException {
  constructor(instanceId: string, regionId?: string) {
    super(
      regionId
        ? `实例 ${instanceId} 在区域 ${regionId} 中不存在`
        : `实例 ${instanceId} 不存在`,
      'INSTANCE_NOT_FOUND',
      HttpStatus.NOT_FOUND,
      { instanceId, regionId },
    );
  }
}

/**
 * 表单数据验证失败异常
 */
export class FormDataInvalidException extends BusinessException {
  constructor(validationErrors: any[]) {
    super(
      '表单数据验证失败',
      'FORM_DATA_INVALID',
      HttpStatus.UNPROCESSABLE_ENTITY,
      { validationErrors },
    );
  }
}

/**
 * 实例已提交异常
 */
export class AlreadySubmittedException extends BusinessException {
  constructor(instanceId: string) {
    super(
      `实例 ${instanceId} 已提交或已审批完成`,
      'ALREADY_SUBMITTED',
      HttpStatus.CONFLICT,
      { instanceId },
    );
  }
}

/**
 * 禁止操作异常
 */
export class ForbiddenOperationException extends BusinessException {
  constructor(operation: string, reason: string) {
    super(
      `禁止执行操作 ${operation}: ${reason}`,
      'FORBIDDEN',
      HttpStatus.FORBIDDEN,
      { operation, reason },
    );
  }
}

/**
 * 无效状态异常
 */
export class InvalidStatusException extends BusinessException {
  constructor(instanceId: string, currentStatus: string, operation: string) {
    super(
      `实例 ${instanceId} 当前状态 ${currentStatus} 不允许执行 ${operation} 操作`,
      'INVALID_STATUS',
      HttpStatus.BAD_REQUEST,
      { instanceId, currentStatus, operation },
    );
  }
}

/**
 * 撤回失败异常
 */
export class WithdrawFailedException extends BusinessException {
  constructor(instanceId: string, reason: string) {
    super(
      `实例 ${instanceId} 撤回失败: ${reason}`,
      'WITHDRAW_FAILED',
      HttpStatus.BAD_REQUEST,
      { instanceId, reason },
    );
  }
}

// ==================== 事务相关异常 ====================

/**
 * 事务执行失败异常
 */
export class TransactionFailedException extends BusinessException {
  constructor(operation: string, reason?: string) {
    super(
      reason
        ? `事务执行失败 (${operation}): ${reason}`
        : `事务执行失败 (${operation})`,
      'TRANSACTION_FAILED',
      HttpStatus.INTERNAL_SERVER_ERROR,
      { operation, reason },
    );
  }
}

// ==================== Webhook 相关异常 ====================

/**
 * Webhook 不存在异常
 */
export class WebhookNotFoundException extends BusinessException {
  constructor(webhookId: string) {
    super(
      `Webhook ${webhookId} 不存在`,
      'WEBHOOK_NOT_FOUND',
      HttpStatus.NOT_FOUND,
      { webhookId },
    );
  }
}
