import '../../../core/api/api_client.dart';
import '../../../core/api/api_exception.dart';
import '../../../core/api/api_paths.dart';
import '../domain/shopping_list_item.dart';

class ShoppingListRepository {
  final ApiClient _api;

  const ShoppingListRepository(this._api);

  Future<List<ShoppingListItem>> fetchOpenItems({String? token}) async {
    try {
      final data = await _api.getJson(ShoppingListApiPaths.items, token: token);
      if (data is! List) {
        throw const ApiException(
          type: ApiErrorType.unknown,
          message: 'Ogiltigt svar från servern.',
        );
      }
      return data
          .map((item) => ShoppingListItem.fromJson(item as Map<String, dynamic>))
          .toList();
    } on ApiException {
      rethrow;
    } catch (_) {
      throw const ApiException(
        type: ApiErrorType.network,
        message: 'Kunde inte hämta inköpslistan.',
      );
    }
  }

  Future<ShoppingListItem> updateStatus({
    required int itemId,
    required bool checked,
    String? token,
  }) async {
    try {
      final data = await _api.patchJson(
        ShoppingListApiPaths.updateStatus(itemId),
        body: {'checked': checked},
        token: token,
      );
      if (data is! Map<String, dynamic>) {
        throw const ApiException(
          type: ApiErrorType.unknown,
          message: 'Ogiltigt svar från servern.',
        );
      }
      return ShoppingListItem.fromJson(data);
    } on ApiException {
      rethrow;
    } catch (_) {
      throw const ApiException(
        type: ApiErrorType.network,
        message: 'Kunde inte uppdatera inköpsrad.',
      );
    }
  }
}
