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

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

/// 벤더 DTO (JSON 직렬화/역직렬화)
class VendorDto {
  VendorDto({
    this.id,
    required this.vendorCode,
    required this.vendorName,
    this.isActive = true,
    this.isDeleted = false,
    this.note,
    this.createdAt,
    this.updatedAt,
  });

  final int? id;
  final String vendorCode;
  final String vendorName;
  final bool isActive;
  final bool isDeleted;
  final String? note;
  final DateTime? createdAt;
  final DateTime? updatedAt;

  factory VendorDto.fromJson(Map<String, dynamic> json) {
    return VendorDto(
      id: json['id'] as int?,
      vendorCode: json['vendor_code'] as String,
      vendorName: json['vendor_name'] 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']),
    );
  }

  Map<String, dynamic> toJson() {
    return {
      if (id != null) 'id': id,
      'vendor_code': vendorCode,
      'vendor_name': vendorName,
      'is_active': isActive,
      'is_deleted': isDeleted,
      'note': note,
      'created_at': createdAt?.toIso8601String(),
      'updated_at': updatedAt?.toIso8601String(),
    };
  }

  Vendor toEntity() => Vendor(
    id: id,
    vendorCode: vendorCode,
    vendorName: vendorName,
    isActive: isActive,
    isDeleted: isDeleted,
    note: note,
    createdAt: createdAt,
    updatedAt: updatedAt,
  );

  static VendorDto fromEntity(Vendor entity) => VendorDto(
    id: entity.id,
    vendorCode: entity.vendorCode,
    vendorName: entity.vendorName,
    isActive: entity.isActive,
    isDeleted: entity.isDeleted,
    note: entity.note,
    createdAt: entity.createdAt,
    updatedAt: entity.updatedAt,
  );

  static PaginatedResult<Vendor> parsePaginated(Map<String, dynamic>? json) {
    final rawItems = JsonUtils.extractList(json, keys: const ['items']);
    final items = rawItems
        .map(VendorDto.fromJson)
        .map((dto) => dto.toEntity())
        .toList(growable: false);
    return PaginatedResult<Vendor>(
      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;
}

Map<String, dynamic> vendorInputToJson(VendorInput input) {
  final map = input.toPayload();
  map.removeWhere((key, value) => value == null);
  return map;
}
