import 'tie_breaker_option.dart';

class Club {
  final String id;
  final String name;
  final String? description;
  final String? logo;
  final String? address;
  final String? location;
  final String? phone;
  final String? email;
  final String? website;
  final int? memberCount;
  final String? ownerId;
  final int? femaleHandicap;
  final String? averageCalculationPeriod;
  final DateTime? createdAt;
  final DateTime? updatedAt;
  
  /// 동점자 처리 옵션 우선순위 목록
  final List<TieBreakerOption>? tieBreakerOptions;

  Club({
    this.id = '',  // 기본값 빈 문자열로 설정
    required this.name,
    this.description,
    this.logo,
    this.address,
    this.location,
    this.phone,
    this.email,
    this.website,
    this.memberCount,
    this.ownerId,
    this.femaleHandicap,
    this.averageCalculationPeriod,
    this.createdAt,
    this.updatedAt,
    this.tieBreakerOptions,
  });

  // JSON 데이터로부터 Club 객체 생성
  factory Club.fromJson(Map<String, dynamic> json) {
    // 동점자 처리 옵션 변환
    List<TieBreakerOption>? tieBreakerOptions;
    if (json['tieBreakerOptions'] != null) {
      try {
        tieBreakerOptions = (json['tieBreakerOptions'] as List)
            .map((option) => TieBreakerOption.fromString(option.toString()))
            .toList();
      } catch (e) {
        tieBreakerOptions = [];
      }
    }
    
    return Club(
      id: json['id'] != null ? json['id'].toString() : '',
      name: json['name'] ?? '',
      description: json['description'],
      logo: json['logo'],
      address: json['address'],
      location: json['location'],
      phone: json['phone'] ?? json['contact'], // contact 필드도 확인
      email: json['email'],
      website: json['website'],
      memberCount: json['memberCount'],
      ownerId: json['ownerId']?.toString(),
      femaleHandicap: json['femaleHandicap'] != null ? int.tryParse(json['femaleHandicap'].toString()) : null,
      averageCalculationPeriod: json['averageCalculationPeriod'],
      createdAt: json['createdAt'] != null ? DateTime.parse(json['createdAt']) : null,
      updatedAt: json['updatedAt'] != null ? DateTime.parse(json['updatedAt']) : null,
      tieBreakerOptions: tieBreakerOptions,
    );
  }

  // Club 객체를 JSON으로 변환
  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'name': name,
      'description': description,
      'logo': logo,
      'address': address,
      'location': location,
      'phone': phone,
      'email': email,
      'website': website,
      'memberCount': memberCount,
      'ownerId': ownerId,
      'femaleHandicap': femaleHandicap,
      'averageCalculationPeriod': averageCalculationPeriod,
      'createdAt': createdAt?.toIso8601String(),
      'updatedAt': updatedAt?.toIso8601String(),
      'tieBreakerOptions': tieBreakerOptions?.map((option) => option.toString().split('.').last).toList(),
    };
  }
}
