<?php
namespace Incoviba\Repository\Inmobiliaria;

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

class Proveedor extends Ideal\Repository
{
    public function __construct(Define\Connection         $connection,
                                protected Service\Persona $personaService)
    {
        parent::__construct($connection);
        $this->setTable('proveedores');
    }

    public function create(?array $data = null): Model\Inmobiliaria\Proveedor
    {
        $map = (new Implement\Repository\MapperParser(['rut', 'digito', 'nombre', 'razon']))
            ->register('contacto_rut', (new Implement\Repository\Mapper())
                ->setProperty('contacto')
                ->setFunction(function($data) {
                    return $this->personaService->getById($data['contacto_rut']);
                })
                ->setDefault(null));
        return $this->parseData(new Model\Inmobiliaria\Proveedor(), $data, $map);
    }
    public function save(Define\Model $model): Model\Inmobiliaria\Proveedor
    {
        $this->saveNew(['rut', 'digito', 'nombre', 'razon', 'contacto_rut'], [
            $model->rut, $model->digito, $model->nombre, $model->razon, $model->contacto?->rut
        ]);
        return $model;
    }

    /**
     * @param Define\Model $model
     * @param array $new_data
     * @return Model\Inmobiliaria\Proveedor
     * @throws Implement\Exception\EmptyResult
     */
    public function edit(Define\Model $model, array $new_data): Model\Inmobiliaria\Proveedor
    {
        return $this->update($model, ['rut', 'digito', 'nombre', 'razon', 'contacto_rut'], $new_data);
    }

    /**
     * @param string $nombre
     * @return Model\Inmobiliaria\Proveedor
     * @throws Implement\Exception\EmptyResult
     */
    public function fetchByNombre(string $nombre): Model\Inmobiliaria\Proveedor
    {
        $query = $this->connection->getQueryBuilder()
            ->select()
            ->from($this->getTable())
            ->where('nombre = :nombre');
        return $this->fetchOne($query, compact('nombre'));
    }

    public function filterData(array $data): array
    {
        return array_intersect_key($data, array_flip(['rut', 'digito', 'nombre', 'razon', 'contacto_rut']));
    }

    protected function getKey(): string
    {
        return 'rut';
    }
}
