<?php
namespace Incoviba\Repository\Proyecto\Broker;

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

class Contact extends Common\Ideal\Repository
{
    public function __construct(Define\Connection $connection, protected Repository\Direccion $direccionRepository)
    {
        parent::__construct($connection);
        $this->setTable('broker_contacts');
    }

    public function create(?array $data = null): Model\Proyecto\Broker\Contact
    {
        $map = (new Common\Implement\Repository\MapperParser(['name', 'email', 'phone']))
            ->register('address_id', (new Common\Implement\Repository\Mapper())
                ->setProperty('address')
                ->setDefault(null)
                ->setFunction(function($data) {
                    if ($data['address_id'] === null) return null;
                    try {
                        return $this->direccionRepository->fetchById($data['address_id']);
                    } catch (Common\Implement\Exception\EmptyResult) {
                        return null;
                    }
                }));
        return $this->parseData(new Model\Proyecto\Broker\Contact(), $data, $map);
    }
    public function save(Define\Model $model): Model\Proyecto\Broker\Contact
    {
        $model->id = $this->saveNew([
            'name', 'email', 'phone', 'address_id'
        ], [
            $model->name, $model->email, $model->phone, $model->address?->id
        ]);
        return $model;
    }
    public function edit(Define\Model $model, array $new_data): Model\Proyecto\Broker\Contact
    {
        return $this->update($model, ['name', 'email', 'phone', 'address_id'], $new_data);
    }

    /**
     * @param string $name
     * @return Model\Proyecto\Broker\Contact
     * @throws Common\Implement\Exception\EmptyResult
     */
    public function fetchByName(string $name): Model\Proyecto\Broker\Contact
    {
        $query = $this->connection->getQueryBuilder()
            ->select()
            ->from($this->getTable())
            ->where('name = :name');
        return $this->fetchOne($query, ['name' => $name]);
    }
}
