import 'dart:convert';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
import 'package:inventory_system/services/api_service.dart';
import 'package:inventory_system/services/session_manager.dart';

class StoreService {
  Future<List<Map<String, dynamic>>> fetchStores() async {
    final url = Uri.parse('${ApiService.baseUrl}/InvMainAPI/StoreList');
    final cookie = SessionManager.instance.getCookie();
    
    try {
      final response = await http.post(
        url,
        headers: {
          'Content-Type': 'application/json',
          if (cookie != null) 'Cookie': cookie,
        },
      );

      if (response.statusCode == 200) {
        return (json.decode(response.body) as List).cast<Map<String, dynamic>>();
      } else {
        throw Exception('Failed to load stores: ${response.statusCode} - ${response.body}');
      }
    } on SocketException {
      throw Exception('No Internet connection');
    } catch (e) {
      debugPrint('Error fetching stores: $e');
      rethrow;
    }
  }

  Future<List<Map<String, dynamic>>> fetchSpecificUserStores(int userId) async {
    final url = Uri.parse('${ApiService.baseUrl}/InvMainAPI/StoreSpecificMasterList/$userId');
    final cookie = SessionManager.instance.getCookie();

    try {
      final response = await http.post(
        url,
        headers: {
          'Content-Type': 'application/json',
          if (cookie != null) 'Cookie': cookie,
        },
      );

      if (response.statusCode == 200) {
        return (json.decode(response.body) as List).cast<Map<String, dynamic>>();
      } else {
        throw Exception('Failed to load user specific stores: ${response.statusCode} - ${response.body}');
      }
    } on SocketException {
      throw Exception('No Internet connection');
    } catch (e) {
      debugPrint('Error fetching user specific stores: $e');
      rethrow;
    }
  }
}
