<?php

namespace domain\PointSale\UserPointSale;

use domain\PointSale\PointSale\PointSale;
use domain\User\User\User;
use domain\_\AbstractBuilder;

class UserPointSaleBuilder extends AbstractBuilder
{
    protected UserPointSaleRepository $userPointSaleRepository;

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

    public function instanciateUserPointSale(User $user, PointSale $pointSale, string $comment = null): UserPointSale
    {
        $userPointSale = new UserPointSale();
        $userPointSale->populatePointSale($pointSale);
        $userPointSale->populateUser($user);

        if($comment) {
            $userPointSale->comment = $comment;
        }

        return $userPointSale;
    }

    public function createUserPointSale(User $user, PointSale $pointSale, string $comment = null): UserPointSale
    {
        $userPointSale = $this->instanciateUserPointSale($user, $pointSale, $comment);
        $this->saveCreate($userPointSale);

        return $userPointSale;
    }

    public function createUserPointSaleIfNotExist(User $user, PointSale $pointSale, string $comment = null): UserPointSale
    {
        return $this->userPointSaleRepository->findOneUserPointSale($user, $pointSale)
            ?? $this->createUserPointSale($user, $pointSale);
    }

    public function deleteUserPointSalesByPointSale(PointSale $pointSale): void
    {
        UserPointSale::deleteAll(['id_point_sale' => $pointSale->id]);
    }
}