import 'dart:convert';
import 'package:didvan/main.dart';
import 'package:didvan/models/story_model.dart';
import 'package:didvan/providers/user.dart';
import 'package:didvan/services/network/request.dart';
import 'package:didvan/services/network/request_helper.dart';
import 'package:http/http.dart' as http;
import 'package:provider/provider.dart';

class StoryService {
  static Future<List<UserStories>> getStories() async {
    final userProvider =
        Provider.of<UserProvider>(navigatorKey.currentContext!, listen: false);
    final userId = userProvider.user.id;
    final token = RequestService.token;

    // اضافه کردن userId به عنوان پارامتر به URL
    final uri = Uri.parse(RequestHelper.storiesV1).replace(queryParameters: {
      'userId': userId.toString(),
    });

    final response = await http.get(
      uri, // استفاده از uri جدید
      headers: {
        'Authorization': 'Bearer $token',
        'Content-Type': 'application/json',
      },
    );

    // ... بقیه کد بدون تغییر باقی می‌ماند
    if (response.statusCode == 200) {
      final decodedBody = utf8.decode(response.bodyBytes);
      final dynamic jsonData = json.decode(decodedBody);

      List<dynamic> storyList;

      if (jsonData is List) {
        storyList = jsonData;
      } else if (jsonData is Map<String, dynamic> &&
          jsonData.containsKey('content')) {
        storyList = jsonData['content'];
      } else {
        throw Exception('Unexpected JSON structure for stories response');
      }

      return storyList.map((json) => UserStories.fromApiJson(json)).toList();
    } else {
      throw Exception(
          'Failed to load stories with status code: ${response.statusCode}');
    }
  }

  static Future<bool> markStoryAsViewed(int storyId, int storyItemId) async {
    final userProvider =
        Provider.of<UserProvider>(navigatorKey.currentContext!, listen: false);
    final userId = userProvider.user.id;

    final service = RequestService(
      RequestHelper.storyActivity,
      body: {
        'userId': userId,
        'storyId': storyId,
        'storyItemId': storyItemId,
      },
    );

    await service.post();
    return service.isSuccess;
  }
}