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

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

class State extends Common\Ideal\Repository
{
    public function __construct(Common\Define\Connection $connection, protected Repository\Proyecto\Broker\Contract $contractRepository)
    {
        parent::__construct($connection);
    }

    public function getTable(): string
    {
        return 'broker_contract_states';
    }

    public function create(?array $data = null): Model\Proyecto\Broker\Contract\State
    {
        $map = (new Common\Implement\Repository\MapperParser())
            ->register('contract_id', (new Common\Implement\Repository\Mapper())
                ->setProperty('contract')
                ->setFunction(function($data) {
                    return $this->contractRepository->fetchById($data['contract_id']);
                }))
            ->register('type', (new Common\Implement\Repository\Mapper())
                ->setFunction(function($data) {
                    return Model\Proyecto\Broker\Contract\State\Type::from($data['type']);
                }))
            ->register('date', new Common\Implement\Repository\Mapper\DateTime('date'));
        return $this->parseData(new Model\Proyecto\Broker\Contract\State(), $data, $map);
    }
    public function save(Common\Define\Model $model): Model\Proyecto\Broker\Contract\State
    {
        $model->id = $this->saveNew(['contract_id', 'date', 'type'], [$model->contract->id, $model->date->format('Y-m-d'), $model->type->value]);
        return $model;
    }
    public function edit(Common\Define\Model $model, array $new_data): Model\Proyecto\Broker\Contract\State
    {
        return $this->update($model, ['contract_id', 'date', 'type'], $new_data);
    }

    /**
     * @param int $contract_id
     * @return array
     * @throws Common\Implement\Exception\EmptyResult
     */
    public function fetchByContract(int $contract_id): array
    {
        $query = $this->connection->getQueryBuilder()
            ->select()
            ->from($this->getTable())
            ->where('contract_id = :contract_id');
        return $this->fetchMany($query, ['contract_id' => $contract_id]);
    }

    /**
     * @param int $contract_id
     * @return Model\Proyecto\Broker\Contract\State
     * @throws Common\Implement\Exception\EmptyResult
     */
    public function fetchActiveByContract(int $contract_id): Model\Proyecto\Broker\Contract\State
    {
        $query = $this->connection->getQueryBuilder()
            ->select()
            ->from($this->getTable())
            ->where('contract_id = :contract_id AND type = :type');
        return $this->fetchOne($query, ['contract_id' => $contract_id, 'type' => Model\Proyecto\Broker\Contract\State\Type::ACTIVE]);
    }
}
