import 'recipe_ingredient.dart';

class Recipe {
  final int id;
  final String title;
  final String? description;
  final String? imageUrl;
  final int? servings;
  final String? instructions;
  final List<RecipeIngredient> ingredients;
  final bool isPublic;
  final int? ownerId;
  final String? ownerUsername;
  final List<int> sharedWithUserIds;

  const Recipe({
    required this.id,
    required this.title,
    this.description,
    this.imageUrl,
    this.servings,
    this.instructions,
    this.ingredients = const [],
    this.isPublic = false,
    this.ownerId,
    this.ownerUsername,
    this.sharedWithUserIds = const [],
  });

  factory Recipe.fromJson(Map<String, dynamic> json) {
    final dynamic rawId = json['id'];
    final dynamic rawTitle = json['title'] ?? json['name'];
    final dynamic rawDescription = json['description'];
    final dynamic rawImageUrl = json['imageUrl'];
    final dynamic rawServings = json['servings'];
    final rawIngredients = json['ingredients'] as List<dynamic>? ?? [];
    final normalizedImageUrl = rawImageUrl?.toString().trim();
    final ownerJson = json['owner'] as Map<String, dynamic>?;
    final sharesJson = json['shares'] as List<dynamic>? ?? const [];

    return Recipe(
      id: rawId is num ? rawId.toInt() : int.parse(rawId.toString()),
      title: (rawTitle ?? '').toString(),
      description: rawDescription == null ? null : rawDescription.toString(),
      imageUrl:
        (normalizedImageUrl == null || normalizedImageUrl.isEmpty)
          ? null
          : normalizedImageUrl,
      servings: rawServings == null
          ? null
          : (rawServings is num
              ? rawServings.toInt()
              : int.tryParse(rawServings.toString())),
      instructions: json['instructions'] as String?,
      ingredients: rawIngredients
          .map((i) => RecipeIngredient.fromJson(i as Map<String, dynamic>))
          .toList(),
        isPublic: json['isPublic'] == true,
        ownerId: ownerJson == null
          ? null
          : (ownerJson['id'] is num
            ? (ownerJson['id'] as num).toInt()
            : int.tryParse('${ownerJson['id']}')),
        ownerUsername: ownerJson?['username']?.toString(),
        sharedWithUserIds: sharesJson
          .map((s) => (s as Map<String, dynamic>)['userId'])
          .whereType<num>()
          .map((id) => id.toInt())
          .toList(),
    );
  }
}
