// ignore_for_file: avoid_print

import 'dart:convert';
import 'package:didvan/models/home_page_content/swot.dart';
import 'package:didvan/services/network/request.dart';
import 'package:didvan/services/network/request_helper.dart';
import 'package:http/http.dart' as http;

class BookmarkService {
  static Future<List<int>> fetchBookmarks() async {
    final response = await http.get(
      Uri.parse('${RequestHelper.baseUrl2}/api/bookmarks'),
      headers: {
        'Authorization': 'Bearer ${RequestService.token}',
      },
    );
    print("fetchBookmarks: ${response.statusCode} - ${response.body}");
    if (response.statusCode == 200) {
      final data = jsonDecode(response.body) as List;
      return data.map<int>((e) => e['postId'] as int).toList();
    } else {
      throw Exception("Failed to fetch bookmarks");
    }
  }

  static Future<List<int>> fetchSwotBookmarks() async {
    final response = await http.get(
      Uri.parse('${RequestHelper.baseUrl2}/api/swot_bookmarks'),
      headers: {
        'Authorization': 'Bearer ${RequestService.token}',
        'Content-Type': 'application/json',
      },
    );
    print("fetchSwotBookmarks: ${response.statusCode} - ${response.body}");
    if (response.statusCode == 200) {
      final data = jsonDecode(response.body) as List;
      return data.map<int>((e) => e['swotId'] as int).toList();
    } else {
      throw Exception("Failed to fetch swot bookmarks");
    }
  }

  static Future<void> addSwotBookmark(int swotId) async {
    final response = await http.post(
      Uri.parse('${RequestHelper.baseUrl2}/api/swot_bookmarks'),
      headers: {
        'Authorization': 'Bearer ${RequestService.token}',
        'Content-Type': 'application/json',
      },
      body: jsonEncode({'swotId': swotId}),
    );

    if (response.statusCode != 200 && response.statusCode != 201) {
      throw Exception("Failed to add swot bookmark");
    }
  }

  static Future<void> removeSwotBookmark(int swotId) async {
    final response = await http.delete(
      Uri.parse('${RequestHelper.baseUrl2}/api/swot_bookmarks/swot/$swotId'),
      headers: {
        'Authorization': 'Bearer ${RequestService.token}',
        'Content-Type': 'application/json',
      },
    );

    if (response.statusCode != 200 && response.statusCode != 204) {
      throw Exception("Failed to remove swot bookmark");
    }
  }

  static Future<List<SwotItem>> fetchBookmarkedSwotItems() async {
    final postIds = await fetchBookmarks();
    final List<SwotItem> items = [];

    for (final postId in postIds) {
      try {
        final response = await http.get(
          Uri.parse("${RequestHelper.baseUrl2}/api/swot_items/$postId"),
          headers: {
            'Authorization': 'Bearer ${RequestService.token}',
            'Content-Type': 'application/json',
          },
        );

        if (response.statusCode == 200) {
          final postData = jsonDecode(response.body);
          items.add(SwotItem.fromJson(postData));
        } else {
          print('Error fetching swot item $postId: ${response.statusCode}');
        }
      } catch (e) {
        print('Error fetching swot item $postId: $e');
      }
    }

    return items;
  }

  static Future<void> addBookmark(int postId) async {
    final response = await http.post(
      Uri.parse('${RequestHelper.baseUrl2}/api/bookmarks'),
      headers: {
        'Authorization': 'Bearer ${RequestService.token}',
        'Content-Type': 'application/json',
      },
      body: jsonEncode({'postId': postId}),
    );

    if (response.statusCode != 200 && response.statusCode != 201) {
      throw Exception("Failed to add bookmark");
    }
  }

  static Future<void> removeBookmark(int postId) async {
    final response = await http.delete(
      Uri.parse('${RequestHelper.baseUrl2}/api/bookmarks/post/$postId'),
      headers: {
        'Authorization': 'Bearer ${RequestService.token}',
        'Content-Type': 'application/json',
      },
    );

    if (response.statusCode != 200 && response.statusCode != 204) {
      throw Exception("Failed to remove bookmark");
    }
  }
}
