<?php
namespace boru\ai\Asset;

class AssetResolver
{
    /** @var AssetStoreInterface */
    protected $store;

    /** @var AssetBindingPolicy */
    protected $policy;

    public function __construct(AssetStoreInterface $store = null, AssetBindingPolicy $policy = null)
    {
        $this->store = $store ? $store : new NullAssetStore();
        $this->policy = $policy ? $policy : new AssetBindingPolicy();
    }

    public function store(AssetStoreInterface $store = null)
    {
        if ($store !== null) {
            $this->store = $store;
            return $this;
        }
        return $this->store;
    }

    public function policy(AssetBindingPolicy $policy = null)
    {
        if ($policy !== null) {
            $this->policy = $policy;
            return $this;
        }
        return $this->policy;
    }

    public function resolveBinding(AssetProviderInterface $provider, Asset $asset, $purpose = null)
    {
        $this->store()->saveAsset($asset);

        $existing = false;
        if ($asset->id()) {
            $existing = $this->store()->findBinding($asset->id(), $provider->providerName(), $purpose);
            if ($existing && !$this->policy()->shouldReuse($existing)) {
                $existing = false;
            }
        }

        $binding = $provider->ensureBinding($asset, $purpose, $existing ? $existing : null);
        if ($asset->id() && !$binding->assetId()) {
            $binding->assetId($asset->id());
        }

        if ($this->policy()->trackLastUsedAt()) {
            $binding->metadata('last_used_at', date('c'));
        }
        $binding->updatedAt(date('c'));
        if (!$binding->createdAt()) {
            $binding->createdAt(date('c'));
        }

        return $this->store()->saveBinding($binding);
    }
}
