<?php

namespace domain\Payment;

use domain\Document\Invoice\Invoice;
use domain\Order\Order\Order;
use domain\Order\Order\OrderSolver;
use domain\Producer\Producer\Producer;
use domain\User\User\User;
use domain\_\AbstractBuilder;

class PaymentBuilder extends AbstractBuilder
{
    protected PaymentSolver $paymentSolver;
    protected OrderSolver $orderSolver;

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

    public function instanciatePayment(
        string $type,
        float $amount,
        Producer $producer,
        User $user = null,
        User $userAction = null,
        string $meanPayment = null,
        string $comment = null,
        string $dateTransaction = null,
        Order $order = null,
        Invoice $invoice = null
    ): Payment
    {
        $payment = new Payment;

        $payment->type = $type;
        $payment->amount = round($amount, 2);
        $payment->populateProducer($producer);
        $payment->setMeanPayment($meanPayment);
        $payment->setComment($comment);
        $payment->setDateTransaction($dateTransaction);

        if($user) {
            $payment->populateUser($user);
        }

        if($userAction) {
            $payment->populateUserAction($userAction);
        }

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

        if($invoice) {
            $payment->populateInvoice($invoice);
        }

        return $payment;
    }

    public function createPayment(
        string $type,
        float $amount,
        Producer $producer,
        User $user = null,
        User $userAction = null,
        string $meanPayment = null,
        string $comment = null,
        string $dateTransaction = null,
        Order $order = null,
        Invoice $invoice = null
    ): ?Payment
    {
        if ($amount > -0.01 && $amount < 0.01) {
            return null;
        }

        $payment = $this->instanciatePayment($type, $amount, $producer, $user, $userAction, $meanPayment, $comment, $dateTransaction, $order, $invoice);
        $payment->setSummary($this->orderSolver->getPaymentComment($payment));
        $this->create($payment);

        return $payment;
    }
}