<?php

namespace CouponsPlus\App\Coupon;

use CouponsPlus\App\Coupon\Tree\Factories\CouponFromClassicCouponFactory;
use WC_Coupon;

class CouponRegistry
{
    /** @var self|null */
    private static ?self $instance = null;

    /** @var array<string, Coupon> */
    private array $coupons = [];

    /** @var CouponFromClassicCouponFactory */
    private CouponFromClassicCouponFactory $couponFactory;

    private function __construct()
    {
        $this->couponFactory = new CouponFromClassicCouponFactory(CouponOffersTracker::getInstance());
    }

    public static function getInstance(): self
    {
        if (self::$instance === null) {
            self::$instance = new self();
        }

        return self::$instance;
    }

    /**
     * Gets a cached Coupon instance or creates a new one.
     *
     * @param WC_Coupon $classicCoupon
     * @return Coupon
     */
    public function get(WC_Coupon $classicCoupon): Coupon
    {
        $code = strtolower($classicCoupon->get_code('edit'));

        if (!isset($this->coupons[$code])) {
            $this->coupons[$code] = $this->couponFactory->create($classicCoupon);
        }

        return $this->coupons[$code];
    }

    /**
     * Clears all cached coupons. Useful for testing.
     */
    public function reset(): void
    {
        $this->coupons = [];
    }

    /**
     * Resets the singleton instance. Useful for testing.
     */
    public static function resetInstance(): void
    {
        self::$instance = null;
    }
}

