<?php

namespace CouponsPlus\App\Coupon\Tree\Factories;

use CouponsPlus\App\Coupon\Coupon;
use CouponsPlus\App\Coupon\CouponOffersTracker;
use CouponsPlus\App\Coupon\CouponRegistry;
use CouponsPlus\App\Coupon\RowsCouponModel;
use CouponsPlus\Original\Collections\Collection;
use CouponsPlus\Original\Environment\Env;
use WC_Coupon;

class CouponFromClassicCouponFactory
{
    protected $modelFactories;
    private $couponOffersTracker;

    public function __construct(CouponOffersTracker $couponOffersTracker)
    {
        $this->couponOffersTracker = $couponOffersTracker;

        /**
         * hard coded for now
         */
        $this->modelFactories = new ModelFactories;
    } 

    public function create(WC_Coupon $classicCoupon) : Coupon
    {
        (string) $modelType = $this->findModelType($classicCoupon);
        (object) $modelFactory = $this->modelFactories->create($modelType);
        (object) $coupon = new Coupon($classicCoupon, $this->couponOffersTracker);
        
        $coupon->setModel($modelFactory->create($coupon));

        return $coupon;
    }

    public function createCouponsPlusCouponsOnly(Collection $classicCoupons) : Collection
    {
        return $classicCoupons->filter(function(WC_Coupon $classicCoupon) : bool {
            /**
             * This one is important because when a coupon is renamed and it was in someones cart,
             * wc will still feed this zombie to us even though it doesnt exist anymore
             */
            $couponActuallyExists = $classicCoupon->get_id(); // 0 on non existing coupons

            return $couponActuallyExists && $this->modelFactories->getTypes()->contain($this->findModelType($classicCoupon));
        })->map(function(WC_Coupon $classicCoupon) : Coupon {
            return CouponRegistry::getInstance()->get($classicCoupon);
        });
    }

    /**
     * This method aint using any members and so it should be in another class, perhaps in the data/finder layer?
     */
    public function findModelType(WC_Coupon $classicCoupon) : string
    {
        //VERY IMPORTANT FOR BACKWARDS COMPATIBILITY
        return $classicCoupon->get_meta(Env::getWithPrefix('model')) ?: RowsCouponModel::TYPE;
    }
}