<?php

namespace common\logic\Ticket\Ticket\Service;

use common\logic\AbstractBuilder;
use common\logic\Producer\Producer\Model\Producer;
use common\logic\Ticket\Ticket\Model\Ticket;
use common\logic\Ticket\TicketMessage\Model\TicketMessage;
use common\logic\Ticket\TicketMessage\Service\TicketMessageBuilder;
use common\logic\Ticket\TicketUser\Service\TicketUserBuilder;
use common\logic\User\User\Model\User;

class TicketBuilder extends AbstractBuilder
{
    protected TicketMessageBuilder $ticketMessageBuilder;
    protected TicketUserBuilder $ticketUserBuilder;

    public function loadDependencies(): void
    {
        $this->ticketMessageBuilder = $this->loadService(TicketMessageBuilder::class);
        $this->ticketUserBuilder = $this->loadService(TicketUserBuilder::class);
    }

    public function instanciateTicket(Producer $producer, User $user): Ticket
    {
        $ticket = new Ticket();

        $ticket->status = Ticket::STATUS_OPEN;
        $ticket->populateProducer($producer);
        $ticket->populateUser($user);

        return $ticket;
    }

    public function createTicket(Producer $producer, User $user): Ticket
    {
        $ticket = $this->instanciateTicket($producer, $user);
        $this->create($ticket);

        return $ticket;
    }

    public function updateTicketStatus(Ticket $ticket, string $status)
    {
        $ticket->status = $status;
        $this->update($ticket);

        $this->updateTicketUpdatedAt($ticket);
    }

    public function closeTicket(Ticket $ticket)
    {
        $this->updateTicketStatus($ticket, Ticket::STATUS_CLOSED);
    }

    public function openTicket(Ticket $ticket)
    {
        $this->updateTicketStatus($ticket, Ticket::STATUS_OPEN);
    }

    public function updateTicketUpdatedAt(Ticket $ticket)
    {
        $ticket->updated_at = date('Y-m-d H:i:s');
        $this->update($ticket);
    }

    public function createTicketMessage(TicketMessage $ticketMessage)
    {
        $this->updateTicketUpdatedAt($ticketMessage->ticket);
        return $this->create($ticketMessage);
    }

    public function viewTicket(Ticket $ticket, User $user)
    {
        $ticketUser = $this->ticketUserBuilder->createTicketUserIfNotExist($ticket, $user);
        $this->ticketUserBuilder->updateTicketUserReadAt($ticketUser);
    }
}