// ============================================================
// RedeemProvider — 核销 Riverpod Providers
// ============================================================

import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../../core/network/api_client.dart';

class RedeemState {
  final bool isLoading;
  final Map<String, dynamic>? result;
  final String? error;

  const RedeemState({this.isLoading = false, this.result, this.error});

  RedeemState copyWith({
    bool? isLoading,
    Map<String, dynamic>? result,
    String? error,
    bool clearError = false,
  }) {
    return RedeemState(
      isLoading: isLoading ?? this.isLoading,
      result: result ?? this.result,
      error: clearError ? null : (error ?? this.error),
    );
  }
}

class RedeemNotifier extends Notifier<RedeemState> {
  @override
  RedeemState build() => const RedeemState();

  Future<void> redeemCoupon(String holdingId) async {
    state = state.copyWith(isLoading: true, clearError: true);
    try {
      final api = ApiClient.instance;
      final resp = await api.post('/api/v1/redemptions', data: {'holdingId': holdingId});
      state = state.copyWith(isLoading: false, result: resp.data['data'] as Map<String, dynamic>?);
    } catch (e) {
      state = state.copyWith(isLoading: false, error: e.toString());
      rethrow;
    }
  }
}

final redeemProvider = NotifierProvider<RedeemNotifier, RedeemState>(RedeemNotifier.new);
