import 'package:test_sa/models/base.dart';
import 'package:test_sa/models/new_models/building.dart';

class Site extends Base {
  Site({
    this.id,
    this.custName,
    this.buildings,
  }) : super(identifier: id?.toString() ?? '', name: custName); // Handle potential null id

  Site.fromJson(dynamic json) {
    id =  json['siteId'] ?? json['id'];
    identifier = id?.toString() ?? ''; // Handle potential null id
    custName =  json['custName']?? json['siteName'];
    name = custName;
    if (json['buildings'] != null) {
      buildings = [];
      json['buildings'].forEach((v) {
        buildings!.add(Building.fromJson(v)); // Use '!' since buildings is initialized here
      });
    }
     else if (json['assetInventoryBuildings'] != null) {
      buildings = [];
      json['assetInventoryBuildings'].forEach((v) {
        buildings!.add(Building.fromJson(v));
      });
    }
  }

  num? id; // Now nullable
  String? custName; // Now nullable
  List<Building>? buildings; // Now nullable

  Site copyWith({
    num? id, // Parameters are now nullable
    String? custName,
    List<Building>? buildings,
  }) =>
      Site(
        id: id ?? this.id,
        custName: custName ?? this.custName,
        buildings: buildings ?? this.buildings,
      );

  Map<String, dynamic> toJson({bool addBuildings = true}) {
    final map = <String, dynamic>{};
    map['id'] = id;
    map['custName'] = custName;
    if (addBuildings) {
      if (buildings != null) {
        map['buildings'] = buildings!.map((v) => v.toJson()).toList(); // Use '!' since buildings could be null
      }
    } else {
      map['buildings'] = [];
    }

    return map;
  }
}
