// 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 SwotService {
  static Future<List<SwotItem>> fetchSwotItems() async {
    final response = await http.get(
      Uri.parse('${RequestHelper.baseUrl2}/api/swot'),
      headers: {
        'Authorization': 'Bearer ${RequestService.token}',
      },
    );

    print("Status Code: ${response.statusCode}");
    
    // decode manually using utf8.decode on bodyBytes
    final decodedBody = utf8.decode(response.bodyBytes);
    print("Decoded Response Body: $decodedBody");

    if (response.statusCode == 200) {
      final jsonData = json.decode(decodedBody);

      if (jsonData['content'] == null || jsonData['content'] is! List) {
        throw Exception('The data structure is wrong.');
      }

      final List<dynamic> items = jsonData['content'];
      return items.map((e) => SwotItem.fromJson(e)).toList();
    } else {
      throw Exception('Error receiving data - statusCode: ${response.statusCode}');
    }
  }
}
