import 'package:feature_wordpress/feature_wordpress.dart';

import '../domain/order.dart';
import '../domain/order_action_result.dart';
import '../domain/order_status.dart';
import '../domain/orders_repository.dart';
import 'woo_commerce_order_mapper.dart';

/// Real [OrdersRepository] backed by the WooCommerce REST API v3.
///
/// Fetches orders from WooCommerce, maps them to domain [Order] objects,
/// and supports status updates, note additions, and order creation.
///
/// Depends on [WooCommerceApiClient] from `feature_wordpress` for HTTP
/// transport and authentication.
class WooCommerceOrdersRepository implements OrdersRepository {
  final WooCommerceApiClient _apiClient;
  final WooCommerceOrderMapper _mapper;

  WooCommerceOrdersRepository({
    required WooCommerceApiClient apiClient,
    WooCommerceOrderMapper mapper = const WooCommerceOrderMapper(),
  }) : _apiClient = apiClient,
       _mapper = mapper;

  @override
  Future<List<Order>> getOrders() async {
    final jsonOrders = await _apiClient.getAllOrders();
    return _mapper.fromJsonList(jsonOrders);
  }

  @override
  Future<Order?> getOrder(String id) async {
    try {
      final json = await _apiClient.getOrder(id);
      return _mapper.fromJson(json);
    } on WooCommerceApiException catch (e) {
      if (e.statusCode == 404) return null;
      rethrow;
    }
  }

  @override
  Future<OrderActionResult> updateOrderStatus(String id, OrderStatus newStatus) async {
    try {
      final wooStatus = WooCommerceOrderMapper.toWooCommerceStatus(newStatus);
      final json = await _apiClient.updateOrderStatus(id, wooStatus);
      final updated = _mapper.fromJson(json);
      return OrderActionResult.success(updated);
    } on WooCommerceApiException catch (e) {
      return OrderActionResult.failure('WooCommerce error ${e.statusCode}: ${e.message}');
    } catch (e) {
      return OrderActionResult.failure('Unexpected error: $e');
    }
  }

  @override
  Future<OrderActionResult> addOrderNote(String id, String note) async {
    if (note.trim().isEmpty) {
      return const OrderActionResult.failure('Note cannot be empty.');
    }
    try {
      // Add the note via the WooCommerce notes endpoint.
      await _apiClient.addOrderNote(id, note.trim());
      // Fetch the updated order to return the refreshed domain object.
      final json = await _apiClient.getOrder(id);
      final updated = _mapper.fromJson(json);
      return OrderActionResult.success(updated);
    } on WooCommerceApiException catch (e) {
      return OrderActionResult.failure('WooCommerce error ${e.statusCode}: ${e.message}');
    } catch (e) {
      return OrderActionResult.failure('Unexpected error: $e');
    }
  }

  @override
  Future<OrderActionResult> createOrder(Order order) async {
    try {
      final body = _mapper.toCreateJson(order);
      final json = await _apiClient.createOrder(body);
      final created = _mapper.fromJson(json);
      return OrderActionResult.success(created);
    } on WooCommerceApiException catch (e) {
      return OrderActionResult.failure('WooCommerce error ${e.statusCode}: ${e.message}');
    } catch (e) {
      return OrderActionResult.failure('Unexpected error: $e');
    }
  }
}
