<?php
namespace Incoviba\Repository\Proyecto;

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

class Broker extends Common\Ideal\Repository
{
    public function getTable(): string
    {
        return 'brokers';
    }
    protected function getIndex(Define\Model $model): mixed
    {
        return $model->rut;
    }
    protected function getKey(): string
    {
        return 'rut';
    }

    public function create(?array $data = null): Model\Proyecto\Broker
    {
        $map = new Common\Implement\Repository\MapperParser(['rut', 'digit', 'name']);
        return $this->parseData(new Model\Proyecto\Broker(), $data, $map);
    }

    public function save(Common\Define\Model $model): Model\Proyecto\Broker
    {
        $this->saveNew(
            ['rut', 'digit', 'name'],
            [$model->rut, $model->digit, $model->name]
        );
        return $model;
    }

    /**
     * @param Define\Model $model
     * @param array $new_data
     * @return Model\Proyecto\Broker
     * @throws Common\Implement\Exception\EmptyResult
     */
    public function edit(Common\Define\Model $model, array $new_data): Model\Proyecto\Broker
    {
        return $this->update($model, ['rut', 'digit', 'name'], $new_data);
    }

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

    /**
     * @param int $promotion_id
     * @return array
     * @throws Common\Implement\Exception\EmptyResult
     */
    public function fetchByPromotion(int $promotion_id): array
    {
        $query = $this->connection->getQueryBuilder()
            ->select('a.*')
            ->from("{$this->getTable()} a")
            ->joined('INNER JOIN promotion_brokers pb ON pb.broker_rut = a.rut')
            ->where('pb.promotion_id = :promotion_id');
        return $this->fetchMany($query, ['promotion_id' => $promotion_id]);
    }
}
