import 'package:dio/dio.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:kasy_kit/core/data/api/base_api_exceptions.dart';
import 'package:kasy_kit/core/data/api/http_client.dart';
import 'package:kasy_kit/features/feedbacks/api/entities/feature_vote_entity.dart';

final featureVoteApiProvider = Provider<FeatureVoteApi>(
  (ref) => FeatureVoteApi(
    client: ref.read(httpClientProvider),
  ),
);

/// REST endpoints expected:
///   GET    /feature-votes          → List<UserFeatureVoteEntity> (filtered by authenticated user)
///   POST   /feature-votes          → UserFeatureVoteEntity  body: {feature_id}
///   DELETE /feature-votes/:id      → 204 No Content
class FeatureVoteApi {
  final HttpClient _client;

  FeatureVoteApi({required HttpClient client}) : _client = client;

  Future<List<UserFeatureVoteEntity>> getUserVotes(String userId) async {
    try {
      final response = await _client.get('/feature-votes');
      final list = response.data as List<dynamic>;
      return list
          .map((e) => UserFeatureVoteEntity.fromJson(e as Map<String, dynamic>))
          .toList();
    } on DioException catch (e) {
      throw ApiError.fromDioException(e);
    } catch (e, s) {
      throw ApiError(code: 0, message: '$e: $s');
    }
  }

  Future<UserFeatureVoteEntity> create(String userId, String featureId) async {
    try {
      final response = await _client.post(
        '/feature-votes',
        data: {'feature_id': featureId},
      );
      return UserFeatureVoteEntity.fromJson(
          response.data as Map<String, dynamic>);
    } on DioException catch (e) {
      throw ApiError.fromDioException(e);
    } catch (e, s) {
      throw ApiError(code: 0, message: '$e: $s');
    }
  }

  Future<void> delete(String featureId, String voteId) async {
    try {
      await _client.delete('/feature-votes/$voteId');
    } on DioException catch (e) {
      throw ApiError.fromDioException(e);
    } catch (e, s) {
      throw ApiError(code: 0, message: '$e: $s');
    }
  }
}
