import 'package:superport_v2/core/common/models/paginated_result.dart';
import 'package:superport_v2/core/common/utils/json_utils.dart';
import 'package:superport_v2/features/approvals/data/dtos/approval_step_dto.dart';
import 'package:superport_v2/features/approvals/domain/entities/approval.dart';

import '../../domain/entities/approval_step_record.dart';

/// 결재 단계 기록 API 응답을 표현하는 DTO.
class ApprovalStepRecordDto {
  ApprovalStepRecordDto({
    required this.approvalId,
    required this.approvalNo,
    this.transactionNo,
    this.templateName,
    required this.step,
  });

  final int approvalId;
  final String approvalNo;
  final String? transactionNo;
  final String? templateName;
  final ApprovalStep step;

  /// JSON에서 필요한 필드를 추출해 DTO를 생성한다.
  factory ApprovalStepRecordDto.fromJson(Map<String, dynamic> json) {
    final approvalData = json['approval'] as Map<String, dynamic>?;
    final approvalId =
        json['approval_id'] as int? ?? approvalData?['id'] as int? ?? 0;
    final approvalNo =
        json['approval_no'] as String? ??
        approvalData?['approval_no'] as String? ??
        approvalData?['approvalNo'] as String? ??
        '-';
    final transactionNo =
        json['transaction_no'] as String? ??
        approvalData?['transaction_no'] as String? ??
        approvalData?['transactionNo'] as String?;
    final templateName =
        json['template_name'] as String? ??
        approvalData?['template_name'] as String? ??
        approvalData?['templateName'] as String?;

    final step = ApprovalStepDto.fromJson(json).toEntity();

    return ApprovalStepRecordDto(
      approvalId: approvalId,
      approvalNo: approvalNo,
      transactionNo: transactionNo,
      templateName: templateName,
      step: step,
    );
  }

  /// DTO를 [ApprovalStepRecord] 엔티티로 변환한다.
  ApprovalStepRecord toEntity() {
    return ApprovalStepRecord(
      approvalId: approvalId,
      approvalNo: approvalNo,
      transactionNo: transactionNo,
      templateName: templateName,
      step: step,
    );
  }

  /// 페이징 응답을 [PaginatedResult] 형태로 반환한다.
  static PaginatedResult<ApprovalStepRecord> parsePaginated(
    Map<String, dynamic>? json,
  ) {
    final rawItems = JsonUtils.extractList(json, keys: const ['items']);
    final items = rawItems
        .map(ApprovalStepRecordDto.fromJson)
        .map((dto) => dto.toEntity())
        .toList(growable: false);

    return PaginatedResult<ApprovalStepRecord>(
      items: items,
      page: JsonUtils.readInt(json, 'page', fallback: 1),
      pageSize: JsonUtils.readInt(json, 'page_size', fallback: items.length),
      total: JsonUtils.readInt(json, 'total', fallback: items.length),
    );
  }
}
