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 DepartmentService {
  Future<List<dynamic>> fetchDepartments() async {
    // *** THE FIX IS HERE: Using the correct AdminAPI endpoint URL as you specified ***
    final uri = Uri.parse('${ApiService.baseUrl}/AdminAPI/GetDepartmentWithCompanyList');
    final cookie = SessionManager.instance.getCookie();
    debugPrint("Fetching departments from: $uri");

    final headers = {
      'Content-Type': 'application/json; charset=UTF-8',
      if (cookie != null) 'Cookie': cookie,
    };

    try {
      final response = await http.post(uri, headers: headers);

      if (response.statusCode == 200) {
        return response.body.isNotEmpty ? jsonDecode(response.body) : [];
      } else {
        throw Exception('Failed to load departments. Status: ${response.statusCode}');
      }
    } on SocketException {
      throw Exception('No Internet connection.');
    } catch (e) {
      debugPrint('Error fetching departments: $e');
      rethrow;
    }
  }
}
