<?php

namespace App\Traits;

use App\SalesChannelType;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Collection;
use Mtc\MercuryDataModels\SalesChannelRule;

trait UsesSalesChannelRules
{
    use AppliesQueryConditions;
    use AppliesModelConditions;

    protected Collection $rules;

    protected function hasSalesChannelRules(SalesChannelType $channel): bool
    {
        return !$this->getSalesChannelRules($channel)->isEmpty();
    }

    protected function getSalesChannelRules(SalesChannelType $channel): Collection
    {
        if (empty($this->rules)) {
            $channel_rules = SalesChannelRule::query()
                ->where('channel', '=', $channel)
                ->first();

            $this->rules = collect($channel_rules ? $channel_rules->conditions : []);
        }

        return $this->rules;
    }

    protected function applyQueryConditionsForChannel(Builder $query, SalesChannelType $channel)
    {
        $this->applyQueryConditions($query, $this->getSalesChannelRules($channel));
    }

    protected function modelPassesChannelConditions($model, SalesChannelType $channel): bool
    {
        return $this->applyModelConditions($model, $this->getSalesChannelRules($channel));
    }
}
