<?php

namespace common\logic\User\CreditHistory\Service;

use common\logic\AbstractBuilder;
use common\logic\Order\Order\Model\Order;
use common\logic\Order\Order\Service\OrderSolver;
use common\logic\Producer\Producer\Model\Producer;
use common\logic\User\CreditHistory\Event\CreditHistoryCreateEvent;
use common\logic\User\CreditHistory\Model\CreditHistory;
use common\logic\User\User\Model\User;
use yii\base\Event;

class CreditHistoryBuilder extends AbstractBuilder
{
    protected CreditHistorySolver $creditHistorySolver;
    protected OrderSolver $orderSolver;

    public function loadDependencies(): void
    {
        $this->creditHistorySolver = $this->loadService(CreditHistorySolver::class);
        $this->orderSolver = $this->loadService(OrderSolver::class);
    }

    public function instanciateCreditHistory(
        string $type,
        float $amount,
        Producer $producer,
        User $user,
        User $userAction,
        string $meanPayment = null,
        Order $order = null
    ): CreditHistory
    {
        $creditHistory = new CreditHistory;

        $creditHistory->type = $type;
        $creditHistory->amount = round($amount, 2);
        $creditHistory->populateProducer($producer);
        $creditHistory->populateUser($user);
        $creditHistory->populateUserAction($userAction);

        if($order) {
            $creditHistory->populateOrder($order);
        }

        if($meanPayment) {
            $creditHistory->mean_payment = $meanPayment;
        }

        return $creditHistory;
    }

    // saveCreditHistory
    public function createCreditHistory(
        string $type,
        float $amount,
        Producer $producer,
        User $user,
        User $userAction,
        string $meanPayment = null,
        Order $order = null
    ): ?CreditHistory
    {
        if ($amount > -0.01 && $amount < 0.01) {
            return null;
        }

        $creditHistory = $this->instanciateCreditHistory($type, $amount, $producer, $user, $userAction, $meanPayment, $order);
        $creditHistory->setComment($creditHistory->getComment() . $this->orderSolver->getCreditHistoryComment($creditHistory));
        $this->saveCreate($creditHistory);

        $creditHistoryCreateEvent = new CreditHistoryCreateEvent();
        $creditHistoryCreateEvent->creditHistory = $creditHistory;
        $creditHistory->trigger(CreditHistory::EVENT_CREATE, $creditHistoryCreateEvent);

        return $creditHistory;
    }
}