<?php

namespace Lc\SovBundle\Repository\Ticket;

use App\Entity\Ticket\Ticket;
use Lc\CaracoleBundle\Repository\SectionStoreTrait;
use Lc\SovBundle\Model\Ticket\TicketInterface;
use Lc\SovBundle\Model\User\UserInterface;
use Lc\SovBundle\Repository\AbstractStore;
use Lc\SovBundle\Repository\RepositoryQueryInterface;

class TicketStore extends AbstractStore implements TicketStoreInterface
{
    protected TicketRepositoryQueryInterface $query;

    public function __construct(TicketRepositoryQueryInterface $query)
    {
        $this->query = $query;
    }

    public function orderByDefault(RepositoryQueryInterface $query): RepositoryQueryInterface
    {
        $query->orderBy('updatedAt', 'DESC');
        return $query;
    }

    public function filtersDefault(RepositoryQueryInterface $query): RepositoryQueryInterface
    {
        return $query;
    }

    public function relationsDefault(RepositoryQueryInterface $query): RepositoryQueryInterface
    {
        return $query;
    }

    // getTicketsByUser
    public function getByUser(UserInterface $user, $query = null): array
    {
        $query = $this->createDefaultQuery($query);
        $query->filterByUser($user);
        return $query->find();
    }

    // findAllOpen
    public function getOpen(int $limit = 0, $query = null): array
    {
        $query = $this->createDefaultQuery($query);

        $query
            ->filterByStatus(Ticket::TICKET_STATUS_OPEN)
            ->limit($limit)
            ->orderBy('.id', 'DESC');

        return $query->find();
    }

    // countAllOpen
    public function countOpen($query = null): string
    {
        $query = $this->createDefaultQuery($query);

        $query
            ->selectCount()
            ->filterByStatus(Ticket::TICKET_STATUS_OPEN);

        return $query->count();
    }

    public function getOneByIdAndVisitorToken(int $id, string $token, $query = null)
    {
        $query = $this->createDefaultQuery($query);

        $query
                ->filterById($id)
                ->filterByVisitorToken($token);

        return $query->findOne();
    }
}
