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

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

/// 권한 그룹(Group) API 응답을 표현하는 DTO.
class GroupDto {
  GroupDto({
    this.id,
    required this.groupName,
    this.description,
    this.isDefault = false,
    this.isActive = true,
    this.isDeleted = false,
    this.note,
    this.createdAt,
    this.updatedAt,
  });

  final int? id;
  final String groupName;
  final String? description;
  final bool isDefault;
  final bool isActive;
  final bool isDeleted;
  final String? note;
  final DateTime? createdAt;
  final DateTime? updatedAt;

  /// JSON에서 그룹 정보를 파싱한다.
  factory GroupDto.fromJson(Map<String, dynamic> json) {
    return GroupDto(
      id: json['id'] as int?,
      groupName: json['group_name'] as String,
      description:
          json['description'] as String? ??
          json['group_description'] as String?,
      isDefault: (json['is_default'] as bool?) ?? false,
      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를 도메인 [Group] 엔티티로 변환한다.
  Group toEntity() => Group(
    id: id,
    groupName: groupName,
    description: description,
    isDefault: isDefault,
    isActive: isActive,
    isDeleted: isDeleted,
    note: note,
    createdAt: createdAt,
    updatedAt: updatedAt,
  );

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