import 'dart:convert';
import 'package:nearledaily/service/dio.dart';
import 'package:nearledaily/helper/logger.dart';
import '../../../constants/api_constants.dart';
import '../../../modules/authentication/auth.dart';
import '../../repository/authentication/location_repo.dart';

class CustomerLocationProvider implements CustomerLocationRepository {
  final CustomDio customDio = CustomDio();

  @override
  Future<List<Authentication>> fetchCustomerLocations(int customerId) async {
    final url = "${ApiConstants.getCustomerLocations}?customerid=$customerId";
    logger.i("GET CustomerLocation URL: $url");

    try {
      final response = await customDio.getData(
        url,
        headers: {
          "x-hasura-admin-secret": "nearle-admin-secret",
          "Content-Type": "application/json",
        },
      );

      if (response != null &&
          response['customerlocations'] != null &&
          (response['customerlocations'] as List).isNotEmpty) {

        final locations = (response['customerlocations'] as List)
            .map((e) => Authentication.fromLocationJson(e))
            .toList();

        logger.i("Locations count: ${locations.length}");
        return locations;

      } else {
        logger.w("No customer locations found for customerId $customerId");
        return [];
      }
    } catch (e) {
      logger.e("Error in fetchCustomerLocations: $e");
      return [];
    }
  }
  // Create new customer location
  @override
  Future<bool> createCustomerLocation({
    required int customerId,
    required String address,
    required String doorNo,
    required String landmark,
    String suburb = "",
    String city = "",
    String state = "",
    String postcode = "",
    String latitude = "",
    String longitude = "",
    String defaultAddress = "Yes",
    int primaryAddress = 1,
    int status = 1,
  }) async {
    final url = "https://fiesta.nearle.app/live/api/v1/mob/customers/createlocations";
    final body = {
      "customerid": customerId,
      "address": address,
      "suburb": suburb,
      "city": city,
      "state": state,
      "landmark": landmark,
      "doorno": doorNo,
      "postcode": postcode,
      "latitude": latitude,
      "longitude": longitude,
      "defaultaddress": defaultAddress,
      "primaryaddress": primaryAddress,
      "status": status
    };

    logger.i("POST CustomerLocation URL: $url");
    logger.i("Request Body: ${jsonEncode(body)}");

    try {
      final response = await customDio.postData(url, body);

      if (response != null && (response['code'] == 200 || response['code'] == 201)) {
        logger.i("CustomerLocation created successfully: ${jsonEncode(response)}");
        return true;
      } else {
        logger.w("Failed to create CustomerLocation: ${jsonEncode(response)}");
        return false;
      }
    } catch (e) {
      logger.e("Error in createCustomerLocation: $e");
      return false;
    }
  }

}
