import 'dart:convert';

/// Top-level response for the menu API
class MenuResponse {
  final bool success; // API call success flag
  final String message; // Response message
  final List<MenuItem> data; // List of menu items
  final dynamic errors; // Error details (if any)
  final int statusCode; // HTTP-like status code
  final DateTime timestamp; // Response timestamp

  MenuResponse({
    required this.success,
    required this.message,
    required this.data,
    this.errors,
    required this.statusCode,
    required this.timestamp,
  });

  /// Creates a MenuResponse from a JSON map
  factory MenuResponse.fromJson(Map<String, dynamic> json) {
    return MenuResponse(
      success: json['success'] as bool? ?? false,
      message: json['message'] as String? ?? '',
      data: (json['data'] as List<dynamic>?)
              ?.map((e) => MenuItem.fromJson(e as Map<String, dynamic>))
              .toList() ??
          <MenuItem>[],
      errors: json['errors'],
      statusCode: json['statusCode'] as int? ?? 0,
      timestamp: DateTime.tryParse(json['timestamp'] as String? ?? '') ??
          DateTime.now(),
    );
  }

  /// Converts the MenuResponse back to JSON map
  Map<String, dynamic> toJson() {
    return {
      'success': success,
      'message': message,
      'data': data.map((e) => e.toJson()).toList(),
      'errors': errors,
      'statusCode': statusCode,
      'timestamp': timestamp.toIso8601String(),
    };
  }

  /// Parse from raw JSON string
  static MenuResponse fromRawJson(String str) =>
      MenuResponse.fromJson(json.decode(str) as Map<String, dynamic>);

  /// Convert to raw JSON string
  String toRawJson() => json.encode(toJson());
}

/// Individual menu item
class MenuItem {
  final String id; // Unique item ID
  final String name; // Display text
  final bool available; // Availability flag
  final String mobileLink; // Mobile navigation link

  MenuItem({
    required this.id,
    required this.name,
    required this.available,
    required this.mobileLink,
  });

  /// Creates MenuItem from JSON map
  factory MenuItem.fromJson(Map<String, dynamic> json) {
    return MenuItem(
      id: json['id'] as String? ?? '',
      name: json['name'] as String? ?? '',
      available: json['available'] as bool? ?? false,
      mobileLink: json['mobileLink'] as String? ?? '',
    );
  }

  /// Converts MenuItem back to JSON
  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'name': name,
      'available': available,
      'mobileLink': mobileLink,
    };
  }
}
