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_request_entity.dart';

final featureRequestApiProvider = Provider<FeatureRequestApi>(
  (ref) => FeatureRequestApi(
    client: ref.read(httpClientProvider),
  ),
);

/// REST endpoints expected:
///   GET  /feature-requests              → List<FeatureRequestEntity> (only active)
///   POST /feature-requests              body: {title, description} → 201 Created
///     Server creates with active: false and stores title/description in all locales.
class FeatureRequestApi {
  final HttpClient _client;

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

  Future<List<FeatureRequestEntity>> getAllActive() async {
    try {
      final response = await _client.get('/feature-requests');
      final list = response.data as List<dynamic>;
      return list
          .map((e) => FeatureRequestEntity.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<String> create({
    required String title,
    required String description,
  }) async {
    try {
      final response = await _client.post(
        '/feature-requests',
        data: {'title': title, 'description': description},
      );
      return (response.data as Map<String, dynamic>)['id'] as String;
    } on DioException catch (e) {
      throw ApiError.fromDioException(e);
    } catch (e, s) {
      throw ApiError(code: 0, message: '$e: $s');
    }
  }
}
