import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../domain/provider/tenant/get_tenant_pro.dart';

class Create_tenant extends GetxController {
  final CustomerTenantsProvider provider = CustomerTenantsProvider();

  var isLoading = false.obs;
  var responseMessage = ''.obs;

  // Get customerId from SharedPreferences
  Future<int?> _getCustomerId() async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.getInt('customerId');
  }

  // Call POST API after scanning QR
  Future<void> createTenantCustomerFromQR({
    required int tenantId,
    required int locationId,
    int status = 1,
  }) async {
    try {
      final customerId = await _getCustomerId();

      if (customerId == null) {
        responseMessage.value = "Customer ID not found";
        return;
      }

      isLoading.value = true;

      final response = await provider.createTenantCustomer(
        tenantId: tenantId,
        locationId: locationId,
        customerId: customerId,
        status: status,
      );

      print("🔸 Tenant API Response: $response");

      if (response == null) {
        responseMessage.value = "No response from server.";
        return;
      }

      // ✅ Check API response structure and handle message properly
      final code = response['code'];
      final message = response['message'] ?? 'Unknown response';

      if (code == 200 || code == 201) {
        responseMessage.value = "Tenant customer created successfully";
      } else if (code == 409) {
        responseMessage.value = "Customer already assigned to this location";
      } else {
        responseMessage.value = "Error: $message";
      }
    } catch (e) {
      responseMessage.value = "Error: $e";
      print('❌ Exception: $e');
    } finally {
      isLoading.value = false;
    }
  }
}
