<?php

namespace common\logic\Ticket\TicketUser\Service;

use common\logic\AbstractBuilder;
use common\logic\Ticket\Ticket\Model\Ticket;
use common\logic\Ticket\TicketUser\Model\TicketUser;
use common\logic\Ticket\TicketUser\Repository\TicketUserRepository;
use common\logic\User\User\Model\User;

class TicketUserBuilder extends AbstractBuilder
{
    protected TicketUserRepository $ticketUserRepository;

    public function loadDependencies(): void
    {
        $this->ticketUserRepository = $this->loadService(TicketUserRepository::class);
    }

    public function instanciateTicketUser(Ticket $ticket, User $user): TicketUser
    {
        $ticketUser = new TicketUser();

        $ticketUser->populateTicket($ticket);
        $ticketUser->populateUser($user);

        return $ticketUser;
    }

    public function createTicketUser(Ticket $ticket, User $user): TicketUser
    {
        $ticketUser = $this->instanciateTicketUser($ticket, $user);
        $this->saveCreate($ticketUser);

        return $ticketUser;
    }

    public function createTicketUserIfNotExist(Ticket $ticket, User $user): TicketUser
    {
        return $this->ticketUserRepository->findOneTicketUser($ticket, $user)
            ?? $this->createTicketUser($ticket, $user);
    }

    public function updateTicketUserReadAt(TicketUser $ticketUser)
    {
        $ticketUser->read_at = date('Y-m-d H:i:s');
        $this->saveUpdate($ticketUser);
    }
}