import 'package:superport_v2/core/common/models/paginated_result.dart';
import 'package:superport_v2/core/common/utils/json_utils.dart';

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

/// 창고(Warehouse) API 응답을 표현하는 DTO.
class WarehouseDto {
  WarehouseDto({
    this.id,
    required this.warehouseCode,
    required this.warehouseName,
    this.zipcode,
    this.addressDetail,
    this.isActive = true,
    this.isDeleted = false,
    this.note,
    this.createdAt,
    this.updatedAt,
  });

  final int? id;
  final String warehouseCode;
  final String warehouseName;
  final WarehouseZipcodeDto? zipcode;
  final String? addressDetail;
  final bool isActive;
  final bool isDeleted;
  final String? note;
  final DateTime? createdAt;
  final DateTime? updatedAt;

  /// JSON에서 창고 정보를 파싱한다.
  factory WarehouseDto.fromJson(Map<String, dynamic> json) {
    return WarehouseDto(
      id: json['id'] as int?,
      warehouseCode: json['warehouse_code'] as String,
      warehouseName: json['warehouse_name'] as String,
      zipcode: json['zipcode'] is Map<String, dynamic>
          ? WarehouseZipcodeDto.fromJson(
              json['zipcode'] as Map<String, dynamic>,
            )
          : null,
      addressDetail: json['address_detail'] as String?,
      isActive: (json['is_active'] as bool?) ?? true,
      isDeleted: (json['is_deleted'] as bool?) ?? false,
      note: json['note'] as String?,
      createdAt: _parseDate(json['created_at']),
      updatedAt: _parseDate(json['updated_at']),
    );
  }

  /// DTO를 JSON 맵으로 직렬화한다.
  Map<String, dynamic> toJson() {
    return {
      if (id != null) 'id': id,
      'warehouse_code': warehouseCode,
      'warehouse_name': warehouseName,
      'zipcode': zipcode?.toJson(),
      'address_detail': addressDetail,
      'is_active': isActive,
      'is_deleted': isDeleted,
      'note': note,
      'created_at': createdAt?.toIso8601String(),
      'updated_at': updatedAt?.toIso8601String(),
    };
  }

  /// DTO를 도메인 [Warehouse] 엔티티로 변환한다.
  Warehouse toEntity() => Warehouse(
    id: id,
    warehouseCode: warehouseCode,
    warehouseName: warehouseName,
    zipcode: zipcode?.toEntity(),
    addressDetail: addressDetail,
    isActive: isActive,
    isDeleted: isDeleted,
    note: note,
    createdAt: createdAt,
    updatedAt: updatedAt,
  );

  /// 페이징 응답을 [PaginatedResult]로 변환한다.
  static PaginatedResult<Warehouse> parsePaginated(Map<String, dynamic>? json) {
    final rawItems = JsonUtils.extractList(json, keys: const ['items']);
    final items = rawItems
        .map(WarehouseDto.fromJson)
        .map((dto) => dto.toEntity())
        .toList(growable: false);
    return PaginatedResult<Warehouse>(
      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),
    );
  }
}

/// 창고 주소에 대한 우편번호 정보를 담는 DTO.
class WarehouseZipcodeDto {
  WarehouseZipcodeDto({
    required this.zipcode,
    this.sido,
    this.sigungu,
    this.roadName,
  });

  final String zipcode;
  final String? sido;
  final String? sigungu;
  final String? roadName;

  /// JSON에서 우편번호 정보를 파싱한다.
  factory WarehouseZipcodeDto.fromJson(Map<String, dynamic> json) {
    return WarehouseZipcodeDto(
      zipcode: json['zipcode'] as String,
      sido: json['sido'] as String?,
      sigungu: json['sigungu'] as String?,
      roadName: json['road_name'] as String?,
    );
  }

  /// DTO를 JSON 맵으로 직렬화한다.
  Map<String, dynamic> toJson() {
    return {
      'zipcode': zipcode,
      'sido': sido,
      'sigungu': sigungu,
      'road_name': roadName,
    };
  }

  /// DTO를 [WarehouseZipcode] 엔티티로 변환한다.
  WarehouseZipcode toEntity() => WarehouseZipcode(
    zipcode: zipcode,
    sido: sido,
    sigungu: sigungu,
    roadName: roadName,
  );
}

/// 문자열/DateTime 값을 파싱해 [DateTime]으로 변환한다.
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;
}

/// 창고 입력 모델을 API 요청 바디로 변환한다.
Map<String, dynamic> warehouseInputToJson(WarehouseInput input) {
  final map = input.toPayload();
  map.removeWhere((key, value) => value == null);
  return map;
}
