import 'dart:convert';

import 'package:http/http.dart';
import 'package:test_sa/models/new_models/department.dart';

import '../controllers/api_routes/api_manager.dart';
import '../controllers/api_routes/urls.dart';
import 'loading_list_notifier.dart';

class DepartmentBySitesProvider extends LoadingListNotifier<Department> {
  List<int> siteIds = [];

  void setSiteIds(List<int> ids) {
    siteIds = ids;
  }

  @override
  Future getData({int? id}) async {
    if (loading ?? false) return -2;
    if (siteIds.isEmpty) {
      items = [];
      notifyListeners();
      return 200;
    }

    loading = true;
    notifyListeners();
    try {
      Response response = await ApiManager.instance.post(
        URLs.getDepartmentsBySites,
        body: {"siteIds": siteIds},
      );
      stateCode = response.statusCode;
      if (response.statusCode >= 200 && response.statusCode < 300) {
        var responseData = json.decode(response.body);
        List departmentListJson = responseData is List ? responseData : responseData['data'] ?? [];
        items = departmentListJson.map((item) => Department.fromJson(item)).toList();
      }
      loading = false;
      notifyListeners();
      return response.statusCode;
    } catch (error) {
      loading = false;
      stateCode = -1;
      notifyListeners();
      return -1;
    }
  }
}
