import '../domain/product_draft.dart';
import '../domain/product_publishing_repository.dart';
import '../domain/publish_status.dart';
import 'woo_commerce_api_client.dart';
import 'wordpress_product_mapper.dart';

/// Real [ProductPublishingRepository] backed by the WooCommerce REST API.
///
/// Supports product retrieval, publishing, and status updates via
/// `PUT /wp-json/wc/v3/products/{id}`.
class WordPressProductPublishingRepository implements ProductPublishingRepository {
  final WooCommerceApiClient _apiClient;
  final WordPressProductMapper _mapper;

  WordPressProductPublishingRepository({
    required WooCommerceApiClient apiClient,
    WordPressProductMapper mapper = const WordPressProductMapper(),
  }) : _apiClient = apiClient,
       _mapper = mapper;

  @override
  Future<List<ProductDraft>> getProductDrafts() async {
    final jsonProducts = await _apiClient.getAllProducts();
    return _mapper.fromJsonList(jsonProducts);
  }

  @override
  Future<ProductDraft> publishDraft(String id) async {
    final json = await _apiClient.updateProduct(id, {'status': 'publish'});
    return _mapper.fromJson(json);
  }

  @override
  Future<ProductDraft> updateProductStatus(String id, PublishStatus status) async {
    final wooStatus = WordPressProductMapper.toWooCommerceStatus(status);
    final json = await _apiClient.updateProduct(id, {'status': wooStatus});
    return _mapper.fromJson(json);
  }

  @override
  Future<ProductDraft> updateProductPrice(String id, double price) async {
    final json = await _apiClient.updateProduct(id, {'regular_price': price.toStringAsFixed(2)});
    return _mapper.fromJson(json);
  }

  @override
  Future<ProductDraft> updateProductName(String id, String name) async {
    final json = await _apiClient.updateProduct(id, {'name': name});
    return _mapper.fromJson(json);
  }

  @override
  Future<ProductDraft> updateProductDescription(String id, String description) async {
    final json = await _apiClient.updateProduct(id, {'description': description});
    return _mapper.fromJson(json);
  }

  @override
  Future<ProductDraft> updateProductCategory(String id, String category) async {
    final json = await _apiClient.updateProduct(id, {
      'categories': [
        {'name': category},
      ],
    });
    return _mapper.fromJson(json);
  }
}
