<?php

namespace domain\Order\ProductOrder;

use domain\Order\Order\Order;
use domain\PointSale\PointSale\PointSale;
use domain\Product\Product\Product;
use domain\Product\Product\ProductSolver;
use domain\User\User\User;
use domain\User\UserProducer\UserProducer;
use domain\_\AbstractBuilder;

class ProductOrderBuilder extends AbstractBuilder
{
    protected ProductSolver $productSolver;

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

    public function instanciateProductOrder(Order $order, Product $product, float $quantity, float $price): ProductOrder
    {
        $productOrder = new ProductOrder();
        $productOrder->populateOrder($order);
        $productOrder->populateProduct($product);
        $productOrder->populateTaxRate($product->taxRate);
        $productOrder->quantity = $quantity;
        $productOrder->price = $price;
        $productOrder->unit = $product->unit;
        $productOrder->step = $product->step;

        return $productOrder;
    }

    public function createProductOrder(Order $order, Product $product, float $quantity, float $price): ProductOrder
    {
        $productOrder = $this->instanciateProductOrder($order, $product, $quantity, $price);
        $this->saveCreate($productOrder);

        return $productOrder;
    }

    public function updateProductOrderPrice(
        ProductOrder $productOrder,
        User         $user = null,
        UserProducer $userProducer = null,
        PointSale    $pointSale = null,
        int          $quantity = 1)
    {
        $productOrder->price = $this->productSolver->getPrice(
            $productOrder->product,
            [
                'user' => $user,
                'user_producer' => $userProducer,
                'point_sale' => $pointSale,
                'quantity' => $quantity
            ]);

        $this->update($productOrder);

        return $productOrder;
    }

    public function updateProductOrderInvoicePrice(ProductOrder $productOrder, array $params = []): void
    {
        $productOrder->invoice_price = $this->productSolver->getPrice($productOrder->product, [
            'user' => (isset($params['user']) && $params['user']) ? $params['user'] : null,
            'user_producer' => (isset($params['user_producer']) && $params['user_producer']) ? $params['user_producer'] : null,
            'point_sale' => (isset($params['point_sale']) && $params['point_sale']) ? $params['point_sale'] : null,
            'quantity' => $productOrder->quantity
        ]);
        $this->update($productOrder);
    }

    public function updateProductOrderInvoicePriceByValue(ProductOrder $productOrder, float $invoicePrice)
    {
        $productOrder->invoice_price = $invoicePrice;
        $this->update($productOrder);
    }

    public function deleteProductOrdersByOrder(Order $order): void
    {
        ProductOrder::deleteAll(['id_order' => $order->id]);
    }
}