<?php
/**
 * Tag Indexer Service
 *
 * Handles the indexing of WooCommerce product tags
 *
 * @package FuseCommerce\Services
 */

namespace FuseCommerce\Services;

use FuseCommerce\Repositories\ProductRepository;

/**
 * Class TagIndexerService
 *
 * Responsible for building tag data for indexing
 */
class TagIndexerService {

	/**
	 * Product repository instance
	 *
	 * @var ProductRepository
	 */
	private ProductRepository $product_repository;

	/**
	 * Constructor
	 *
	 * @param ProductRepository $product_repository Product repository instance.
	 */
	public function __construct( ProductRepository $product_repository ) {
		$this->product_repository = $product_repository;
	}

	/**
	 * Build tags list
	 *
	 * Builds a flat list of all product tags used by published products
	 *
	 * @return array Array of tag objects with id, name, slug, and count
	 */
	public function buildTagsList(): array {
		// Get only tags used by published products
		$used_tag_ids = $this->product_repository->getUsedTagIds();

		if ( empty( $used_tag_ids ) ) {
			return [];
		}

		$terms = get_terms(
			[
				'taxonomy'   => 'product_tag',
				'include'    => $used_tag_ids,
				'hide_empty' => false,
				'orderby'    => 'name',
				'order'      => 'ASC',
			]
		);

		if ( is_wp_error( $terms ) || empty( $terms ) ) {
			return [];
		}

		$tags = [];
		foreach ( $terms as $term ) {
			$tags[] = [
				'id'    => $term->term_id,
				'name'  => $term->name,
				'slug'  => $term->slug,
				'count' => $term->count,
			];
		}

		return $tags;
	}
}
