<?php
namespace Incoviba\Repository;

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

class Inmobiliaria extends Ideal\Repository
{
    public function __construct(Define\Connection $connection, protected Repository\Banco $bancoRepository, protected Repository\Inmobiliaria\TipoSociedad $tipoSociedadRepository)
    {
        parent::__construct($connection);
        $this->setTable('inmobiliaria');
    }

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

    public function create(?array $data = null): Define\Model
    {
        $map = (new Implement\Repository\MapperParser(['dv', 'razon', 'abreviacion', 'cuenta']))
            ->register('banco', (new Implement\Repository\Mapper())
                ->setFunction(function($data) {
                    return $this->bancoRepository->fetchById($data['banco']);
                }))
            ->register('sociedad', (new Implement\Repository\Mapper())
                ->setProperty('tipoSociedad')
                ->setFunction(function($data) {
                    return $this->tipoSociedadRepository->fetchById($data['sociedad']);
                }));
        return $this->parseData(new Model\Inmobiliaria(), $data, $map);
    }
    public function save(Define\Model $model): Define\Model
    {
        $model->rut = $this->saveNew(
            ['dv', 'razon', 'abreviacion', 'cuenta', 'banco', 'sociedad'],
            [$model->dv, $model->razon, $model->abreviacion, $model->cuenta, $model->banco->id, $model->tipoSociedad->id]
        );
        return $model;
    }
    public function edit(Define\Model $model, array $new_data): Define\Model
    {
        return $this->update($model, ['dv', 'razon', 'abreviacion', 'cuenta', 'banco', 'sociedad'], $new_data);
    }
}
