import 'dart:convert';

import 'package:http/http.dart' as http;
import 'package:test_sa/controllers/api_routes/urls.dart';
import 'package:test_sa/modules/signup/models/company_model.dart';
import 'package:test_sa/providers/loading_list_notifier.dart';

class CompanyProvider extends LoadingListNotifier<Company> {
  @override
  Future getData({int? id}) async {
    if (id == null) {
      items = [];
      notifyListeners();
      return 200;
    }

    if (loading) return -2;
    loading = true;
    notifyListeners();

    try {
      // Use direct HTTP call without authentication token
      final headers = {
        'Content-Type': 'application/json',
        'X-Timezone-Offset': DateTime.now().timeZoneOffset.toString().split(".").first,
      };

      final url = '${URLs.signUpGetCompaniesByAssetGroup}?assetGroupId=$id';
      final response = await http.get(
        Uri.parse(url),
        headers: headers,
      );

      stateCode = response.statusCode;

      if (response.statusCode >= 200 && response.statusCode < 300) {
        List categoriesListJson = json.decode(response.body)["data"];
        items = categoriesListJson.map((item) => Company.fromJson(item)).toList();
      }

      loading = false;
      notifyListeners();
      return response.statusCode;
    } catch (error) {
      loading = false;
      stateCode = -1;
      notifyListeners();
      return -1;
    }
  }
}
