import 'package:dartz/dartz.dart';
import 'package:hmg_patient_app_new/core/api/api_client.dart';
import 'package:hmg_patient_app_new/core/api_consts.dart';
import 'package:hmg_patient_app_new/core/common_models/generic_api_model.dart';
import 'package:hmg_patient_app_new/core/exceptions/api_failure.dart';
import 'package:hmg_patient_app_new/core/location_util.dart';
import 'package:hmg_patient_app_new/features/weather/models/waether_cities_model.dart';
import 'package:hmg_patient_app_new/services/logger_service.dart';

abstract class WeatherRepo {
  Future<Either<Failure, GenericApiModel<List<GetCityInfoList>>>> getCityInfo();
}

class WeatherRepoImp implements WeatherRepo {
  final ApiClient apiClient;
  final LoggerService loggerService;

  WeatherRepoImp({required this.loggerService, required this.apiClient});

  @override
  Future<Either<Failure, GenericApiModel<List<GetCityInfoList>>>> getCityInfo() async {
    Map<String, dynamic> request = {};

    try {
      GenericApiModel<List<GetCityInfoList>>? apiResponse;
      Failure? failure;
      await apiClient.post(
        WEATHER_INDICATOR,
        body: request,
        onFailure: (error, statusCode, {messageStatus, failureType}) {
          failure = failureType;
        },
        onSuccess: (response, statusCode, {messageStatus, errorMessage}) {
          try {
            loggerService.logInfo("Weather API Response: $response");
            final list = response['GetCityInfo_List'];

            if (list == null || list.isEmpty) {
              loggerService.logInfo("Weather API returned empty or null list");
              // Return empty list if no city info
              apiResponse = GenericApiModel<List<GetCityInfoList>>(
                messageStatus: messageStatus,
                statusCode: statusCode,
                errorMessage: null,
                data: [],
              );
              return;
            }

            loggerService.logInfo("Parsing ${list.length} city info items");
            final cityInfoList = list.map((item) => GetCityInfoList.fromJson(item as Map<String, dynamic>)).toList().cast<GetCityInfoList>();

            apiResponse = GenericApiModel<List<GetCityInfoList>>(
              messageStatus: messageStatus,
              statusCode: statusCode,
              errorMessage: null,
              data: cityInfoList,
            );
          } catch (e) {
            loggerService.logError("Error parsing weather data: $e");
            failure = DataParsingFailure(e.toString());
          }
        },
      );
      if (failure != null) return Left(failure!);
      if (apiResponse == null) return Left(ServerFailure("Unknown error"));
      return Right(apiResponse!);
    } catch (e) {
      return Left(UnknownFailure(e.toString()));
    }
  }
}
