<?php
namespace Incoviba\Repository\Inmobiliaria;

use Incoviba\Common\Define;
use Incoviba\Common\Ideal;
use Incoviba\Common\Implement;
use Incoviba\Model;
use Incoviba\Repository;

class AgenteTipo extends Ideal\Repository
{
    public function __construct(Define\Connection $connection, protected Agente $agenteRepository,
                                protected TipoAgente $tipoAgenteRepository)
    {
        parent::__construct($connection);
        $this->setTable('agente_tipo');
    }

    public function create(?array $data = null): Model\Inmobiliaria\AgenteTipo
    {
        $map = (new Implement\Repository\MapperParser())
            ->register('agente', (new Implement\Repository\Mapper())
                ->setFunction(function(?array $data) {
                    return ($data === null) ? null : $this->agenteRepository->fetchById($data['agente']);
                }))
            ->register('tipo', (new Implement\Repository\Mapper())
                ->setProperty('tipoAgente')
                ->setFunction(function(?array $data) {
                    return ($data === null) ? null : $this->tipoAgenteRepository->fetchById($data['tipo']);
                }));
        return $this->parseData(new Model\Inmobiliaria\AgenteTipo(), $data, $map);
    }
    public function save(Define\Model $model): Model\Inmobiliaria\AgenteTipo
    {
        $model->id = $this->saveNew(['agente', 'tipo'], [
            $model->agente->id, $model->agenteTipo->id
        ]);
        return $model;
    }
    public function edit(Define\Model $model, array $new_data): Model\Inmobiliaria\AgenteTipo
    {
        return $this->update($model, ['agente', 'tipo'], $new_data);
    }

    public function fetchByAgente(int $agente_id): array
    {
        $query = $this->connection->getQueryBuilder()
            ->select()
            ->from($this->getTable())
            ->where('agente = ?');
        return $this->fetchMany($query, [$agente_id]);
    }
    public function fetchByTipo(int $tipo_agente_id): array
    {
        $query = $this->connection->getQueryBuilder()
            ->select()
            ->from($this->getTable())
            ->where('tipo = ?');
        return $this->fetchMany($query, [$tipo_agente_id]);
    }
    public function fetchByAgenteAndTipo(int $agente_id, int $tipo_agente_id): Model\Inmobiliaria\AgenteTipo
    {
        $query = $this->connection->getQueryBuilder()
            ->select()
            ->from($this->getTable())
            ->where('agente = ? AND tipo = ?');
        return $this->fetchOne($query, [$agente_id, $tipo_agente_id]);
    }
}
