<?php

namespace CouponsPlus\App\Coupon\Attributes\Factories;

use WP_Term;
use WC_Product_Attribute;
use CouponsPlus\Original\Collections\Collection;
use CouponsPlus\App\Coupon\Attributes\Data\GlobalAttributeData;

class GlobalAttributeDataFactory
{
    /**
     * @param int|string $attributeIdOrSlug
     * @param array|null $valuesToUse
     * @return GlobalAttributeData
     */
    public function create($attributeIdOrSlug, array $valuesToUse = null) : GlobalAttributeData
    {
        $attributeData = wc_get_attribute(
            is_int($attributeIdOrSlug) ? $attributeIdOrSlug : wc_attribute_taxonomy_id_by_name($attributeIdOrSlug)
        );

        $WC_Product_Attribute = new WC_Product_Attribute();

        $WC_Product_Attribute->set_id($attributeData->id);
        $WC_Product_Attribute->set_name($attributeData->name);

        $WC_Product_Attribute->set_options(Collection::create(get_terms(['taxonomy' => "{$attributeData->slug}", 'hide_empty' => false])
        )->map(function (WP_Term $term): int {
            return $term->term_id;
        })->asArray()
        );

        $globalAttributeData = new GlobalAttributeData(
            $WC_Product_Attribute,
            new GlobalAttributeValueDataFactory()
        );

        if (is_array($valuesToUse)) {
            $globalAttributeData->useValues($valuesToUse);
        }

        return $globalAttributeData;
    }
}