import 'package:autos/core/constants/api_endpoints.dart';
import 'package:autos/data/models/turn14_model.dart';
import 'package:autos/data/sources/remote/api_service.dart';
import 'package:autos/domain/entities/turn14.dart';
import 'package:dio/dio.dart';

abstract class Turn14Repository {
  /// Save Turn14 credentials
  Future<Turn14Entity> save({
    required String userId,
    required String clientId,
    required String clientSecret,
  });
}

class Turn14RepositoryImpl implements Turn14Repository {
  final ApiService _apiService;

  Turn14RepositoryImpl(this._apiService);

  @override
  Future<Turn14Entity> save({
    required String userId,
    required String clientId,
    required String clientSecret,
  }) async {
    try {
      final response = await _apiService.post(ApiEndpoints.turn14Save, {
        "userid": userId,
        "turn14clientid": clientId,
        "turn14clientsecret": clientSecret,
      });

      // Check status
      if (response.statusCode == 200) {
        final data = response.data;

        if (data['code'] == "TURN14_SAVED") {
          /// Convert Response → Entity
          return Turn14StatusModel.fromJson(data).toEntity();
        } else {
          throw Exception(
            data['message'] ?? "Failed to save Turn14 credentials",
          );
        }
      } else {
        throw Exception("Server error: ${response.statusCode}");
      }
    } on DioException catch (e) {
      throw Exception("Network error: ${e.message}");
    } catch (e) {
      throw Exception("Unexpected error: $e");
    }
  }

  Future<Turn14Entity> status(String userId) async {
    try {
      final response = await _apiService.post(ApiEndpoints.turn14Status, {
        "userid": userId,
      });

      if (response.statusCode == 200) {
        final data = response.data;

        if (data["code"] == "TURN14_STATUS") {
          return Turn14StatusModel.fromJson(data).toEntity();
        } else {
          throw Exception(data["message"] ?? "Failed to fetch Turn14 status");
        }
      } else {
        throw Exception("Server error: ${response.statusCode}");
      }
    } catch (e) {
      throw Exception("Network/Unexpected error: $e");
    }
  }
}
