import 'package:syncrow_web/pages/spaces_management/all_spaces/model/product_model.dart';
import 'package:syncrow_web/utils/constants/action_enum.dart';
import 'package:uuid/uuid.dart';

import 'tag.dart';

class SubspaceModel {
  final String? uuid;
  String subspaceName;
  final bool disabled;
  List<Tag>? tags;
  String internalId;

  SubspaceModel({
    this.uuid,
    required this.subspaceName,
    required this.disabled,
    this.tags,
    String? internalId,
  }) : internalId = internalId ?? const Uuid().v4();

  factory SubspaceModel.fromJson(Map<String, dynamic> json) {
    final String internalId = json['internalId'] ?? const Uuid().v4();

    return SubspaceModel(
      uuid: json['uuid'] ?? '',
      subspaceName: json['subspaceName'] ?? '',
      disabled: json['disabled'] ?? false,
      internalId: internalId,
      tags: (json['productAllocations'] as List<dynamic>?)
              ?.map((item) => Tag.fromJson(item))
              .toList() ??
          [],
    );
  }

  Map<String, dynamic> toJson() {
    return {
      if (uuid != null) 'uuid': uuid,
      'subspaceName': subspaceName,
      'disabled': disabled,
      'tags': tags?.map((e) => e.toJson()).toList() ?? [],
    };
  }
}

class UpdateSubspaceModel {
  final String uuid;
  final Action action;
  final String? subspaceName;
  final List<UpdateTag>? tags;
  UpdateSubspaceModel({
    required this.action,
    required this.uuid,
    this.subspaceName,
    this.tags,
  });

  factory UpdateSubspaceModel.fromJson(Map<String, dynamic> json) {
    return UpdateSubspaceModel(
      action: ActionExtension.fromValue(json['action']),
      uuid: json['uuid'] ?? '',
      subspaceName: json['subspaceName'] ?? '',
      tags: (json['tags'] as List)
          .map((item) => UpdateTag.fromJson(item))
          .toList(),
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'action': action.value,
      'uuid': uuid,
      'subspaceName': subspaceName,
      'tags': tags?.map((e) => e.toJson()).toList() ?? [],
    };
  }
}

class UpdateTag {
  final Action action;
  final String? uuid;
  final String tag;
  final bool disabled;
  final ProductModel? product;

  UpdateTag({
    required this.action,
    this.uuid,
    required this.tag,
    required this.disabled,
    this.product,
  });

  factory UpdateTag.fromJson(Map<String, dynamic> json) {
    return UpdateTag(
      action: ActionExtension.fromValue(json['action']),
      uuid: json['uuid'] ?? '',
      tag: json['tag'] ?? '',
      disabled: json['disabled'] ?? false,
      product: json['product'] != null
          ? ProductModel.fromMap(json['product'])
          : null,
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'action': action.value,
      'uuid': uuid,
      'tag': tag,
      'disabled': disabled,
      'product': product?.toMap(),
    };
  }
}
