<?php

namespace Velis\Repository\Bpm\Ticket;

use ArrayAccess;
use Velis\Bpm\Ticket\Factory;
use Velis\Bpm\Ticket\Ticket;
use Velis\Db\EntityRepository;
use Velis\Exception\WrongTicketTypeException;

/**
 * @author Jan Małysiak <jan.malysiak@velistech.com>
 *
 * @extends EntityRepository<Ticket>
 */
class TicketRepository extends EntityRepository
{
    /**
     * {@inheritDoc}
     * @throws WrongTicketTypeException
     */
    protected function createEntityInstance(array|ArrayAccess $data)
    {
        $instance = Factory::create($data);

        if (!$instance instanceof $this->entityClass) {
            throw new WrongTicketTypeException(sprintf('Ticket #%s is not instance of %s', $instance->id(), $this->entityClass));
        }

        return $instance;
    }

    /**
     * {@inheritDoc}
     */
    public function findBy(array $criteria, ?array $orderBy = null, $limit = null, $offset = null): array
    {
        $ticketTypeId = defined("$this->entityClass::TICKET_TYPE") ? $this->entityClass::TICKET_TYPE : null;
        if ($ticketTypeId) {
            $criteria['ticket_type_id'] = $ticketTypeId;
        }

        return parent::findBy($criteria, $orderBy, $limit, $offset);
    }
}
