<?php

namespace Velis\Model\RelationLoader\Relations;

use Velis\Model\DataObject;

/**
 * One-to-One database relation logical class.
 *
 * @author Szymon Janaczek <szymon.janaczek@velistech.com>
 *
 * @template TRelatedModel of DataObject
 * @template TTargetModel of DataObject
 * @extends HasManyOrOneThrough<TRelatedModel, TTargetModel>
 */
class HasOneThroughRelation extends HasManyOrOneThrough
{
    /**
     * @param TTargetModel $targetModel
     * @param TRelatedModel[] $relatedModels
     * @return TRelatedModel|null
     */
    protected function getRelatedModels(DataObject $targetModel, array $relatedModels)
    {
        // If the Target Model does not have a local key field, return null.
        if (!isset($targetModel[$this->foreignKey])) {
            return null;
        }

        if (is_array($relatedModels[$targetModel[$this->foreignKey]])) {
            return reset($relatedModels[$targetModel[$this->foreignKey]]) ?: null;
        }

        return null;
    }

    public function getOne()
    {
        return $this->get();
    }

    /**
     * @return TRelatedModel
     */
    public function get()
    {
        $data = parent::get();
        if (is_array($data)) {
            return reset($data);
        }

        return null;
    }
}
