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_audit_dto.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_history_record.dart';

/// 결재 이력(History) API 응답을 표현하는 DTO.
class ApprovalHistoryRecordDto {
  ApprovalHistoryRecordDto({
    required this.id,
    required this.approvalId,
    required this.approvalNo,
    this.stepOrder,
    required this.action,
    this.fromStatus,
    required this.toStatus,
    required this.approver,
    required this.actionAt,
    this.note,
  });

  final int id;
  final int approvalId;
  final String approvalNo;
  final int? stepOrder;
  final ApprovalAction action;
  final ApprovalStatus? fromStatus;
  final ApprovalStatus toStatus;
  final ApprovalApprover approver;
  final DateTime actionAt;
  final String? note;

  /// 원본 JSON에서 필드를 파싱해 DTO를 생성한다.
  factory ApprovalHistoryRecordDto.fromJson(Map<String, dynamic> json) {
    final approvalData = json['approval'] as Map<String, dynamic>?;
    final id = json['id'] as int? ?? 0;
    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 stepOrder =
        json['step_order'] as int? ??
        (json['step'] as Map<String, dynamic>?)?['step_order'] as int?;
    final action = ApprovalActionDto.fromJson(
      json['action'] as Map<String, dynamic>? ?? const {},
    ).toEntity();
    final fromStatus = json['from_status'] is Map<String, dynamic>
        ? ApprovalStatusDto.fromJson(
            json['from_status'] as Map<String, dynamic>,
          ).toEntity()
        : null;
    final toStatus = ApprovalStatusDto.fromJson(
      json['to_status'] as Map<String, dynamic>? ?? const {},
    ).toEntity();
    final approver = ApprovalApproverDto.fromJson(
      json['approver'] as Map<String, dynamic>? ?? const {},
    ).toEntity();
    final actionAt = _parseDate(json['action_at']) ?? DateTime.now();
    final note = json['note'] as String?;

    return ApprovalHistoryRecordDto(
      id: id,
      approvalId: approvalId,
      approvalNo: approvalNo,
      stepOrder: stepOrder,
      action: action,
      fromStatus: fromStatus,
      toStatus: toStatus,
      approver: approver,
      actionAt: actionAt,
      note: note,
    );
  }

  /// DTO를 도메인 [ApprovalHistoryRecord] 엔티티로 변환한다.
  ApprovalHistoryRecord toEntity() {
    return ApprovalHistoryRecord(
      id: id,
      approvalId: approvalId,
      approvalNo: approvalNo,
      stepOrder: stepOrder,
      action: action,
      fromStatus: fromStatus,
      toStatus: toStatus,
      approver: approver,
      actionAt: actionAt,
      note: note,
    );
  }

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

    return PaginatedResult<ApprovalHistoryRecord>(
      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),
    );
  }
}

/// 다양한 형식으로 전달될 수 있는 날짜 값을 파싱한다.
DateTime? _parseDate(Object? value) {
  if (value == null) return null;
  if (value is DateTime) return value;
  if (value is String) return DateTime.tryParse(value);
  return null;
}
