import '../domain/product_category.dart';
import '../domain/product_draft.dart';
import '../domain/product_image.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, status updates, product creation,
/// deletion, image management, and category CRUD via the WooCommerce REST API.
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);
  }

  // ── Stage 9C: Catalog expansion ──────────────────────────────────────────

  @override
  Future<ProductDraft> createProduct({
    required String name,
    required double price,
    String description = '',
    String sku = '',
    int? categoryId,
    PublishStatus status = PublishStatus.draft,
  }) async {
    final wooStatus = status == PublishStatus.unpublished
        ? 'draft'
        : WordPressProductMapper.toWooCommerceStatus(status);

    final body = <String, dynamic>{
      'name': name,
      'regular_price': price.toStringAsFixed(2),
      'status': wooStatus,
    };

    if (description.isNotEmpty) body['description'] = description;
    if (sku.isNotEmpty) body['sku'] = sku;
    if (categoryId != null) {
      body['categories'] = [
        {'id': categoryId},
      ];
    }

    final json = await _apiClient.createProduct(body);
    return _mapper.fromJson(json);
  }

  @override
  Future<void> deleteProduct(String id, {bool force = false}) async {
    await _apiClient.deleteProduct(id, force: force);
  }

  @override
  Future<ProductDraft> updateProductImages(String id, List<int> imageIds) async {
    final json = await _apiClient.setProductImages(id, imageIds);
    return _mapper.fromJson(json);
  }

  @override
  Future<List<ProductCategory>> getCategories() async {
    final jsonCategories = await _apiClient.getCategories();
    return jsonCategories.map(_mapCategory).toList();
  }

  @override
  Future<ProductCategory> createCategory({required String name, int parentId = 0}) async {
    final body = <String, dynamic>{'name': name};
    if (parentId != 0) body['parent'] = parentId;

    final json = await _apiClient.createCategory(body);
    return _mapCategory(json);
  }

  @override
  Future<ProductCategory> updateCategory(int categoryId, {String? name, int? parentId}) async {
    final body = <String, dynamic>{};
    if (name != null) body['name'] = name;
    if (parentId != null) body['parent'] = parentId;

    final json = await _apiClient.updateCategory(categoryId, body);
    return _mapCategory(json);
  }

  @override
  Future<void> deleteCategory(int categoryId, {bool force = true}) async {
    await _apiClient.deleteCategory(categoryId, force: force);
  }

  @override
  Future<List<ProductImage>> getProductImages(String id) async {
    final jsonImages = await _apiClient.getProductImages(id);
    return jsonImages.asMap().entries.map((entry) {
      final img = entry.value;
      return ProductImage(
        id: (img['id'] as num?)?.toInt() ?? 0,
        url: (img['src'] as String?) ?? '',
        alt: (img['alt'] as String?) ?? '',
        position: entry.key,
      );
    }).toList();
  }

  // ── Private helpers ───────────────────────────────────────────────────────

  /// Maps a WooCommerce category JSON map to a [ProductCategory].
  static ProductCategory _mapCategory(Map<String, dynamic> json) {
    return ProductCategory(
      id: (json['id'] as num?)?.toInt() ?? 0,
      name: (json['name'] as String?) ?? '',
      slug: (json['slug'] as String?) ?? '',
      parentId: (json['parent'] as num?)?.toInt() ?? 0,
      count: (json['count'] as num?)?.toInt() ?? 0,
    );
  }
}
