import 'dart:convert';
import 'package:http/http.dart' as http;

import 'package:f0ckapp/models/mediaitem.dart';

Future<List<MediaItem>> fetchMedia({
  String? older,
  String? type,
  int? mode,
  bool? random,
}) async {
  final Uri url = Uri.parse('https://api.f0ck.me/items/get').replace(
    queryParameters: {
      'type': type ?? 'image',
      'mode': (mode ?? 0).toString(),
      'random': (random! ? 1 : 0).toString(),
      if (older != null) 'older': older,
    },
  );

  final response = await http.get(url);
  if (response.statusCode == 200) {
    final List<dynamic> jsonList = jsonDecode(response.body);
    return jsonList.map((item) => MediaItem.fromJson(item)).toList();
  } else {
    throw Exception('Fehler beim Abrufen der Medien: ${response.statusCode}');
  }
}

Future<MediaItem> fetchMediaDetail(int itemId) async {
  final Uri url = Uri.parse('https://api.f0ck.me/item/${itemId.toString()}');

  final response = await http.get(url);
  if (response.statusCode == 200) {
    final Map<String, dynamic> jsonResponse = jsonDecode(response.body);

    return MediaItem.fromJson(jsonResponse);
  } else {
    throw Exception(
      'Fehler beim Abrufen der Media-Details: ${response.statusCode}',
    );
  }
}
