<?php

namespace App\Domains\Invoice\Actions\UpdateInvoice;

use App\Domains\Invoice\Actions\ChangeStatus\ChangeStatusCommand;
use App\Domains\Invoice\Actions\ChangeStatus\ChangeStatusRequest;
use App\Enumerations\InvoiceStatus;
use App\ValueObjects\Amount;

class UpdateInvoiceCommand {
    private UpdateInvoiceRequest $request;

    public function __construct(UpdateInvoiceRequest $request) {
        $this->request = $request;
    }

    public function execute() : UpdateInvoiceResponse {
        $response = new UpdateInvoiceResponse();
        $changes = $this->request->invoice->changes ?? '';

        if ($this->request->invoice->amount !==  $this->request->amount->getAmount()) {
            $changes .= 'Betrag geändert von ' . Amount::fromString($this->request->invoice->amount)->toString() . ' auf ' . Amount::fromString($this->request->amount->getAmount())->toString() . '.<br />';
            $this->request->invoice->amount = $this->request->amount->getAmount();
        }

        if ($this->request->invoice->invoiceType()->slug !== $this->request->invoiceType->slug) {
            $changes .= 'Abrechnungstyp geändert von ' . $this->request->invoice->invoiceType()->name . ' auf ' . $this->request->invoiceType->name . '.<br />';
            $this->request->invoice->type = $this->request->invoiceType->slug;
        }

        if ($this->request->invoice->costUnit()->first()->id !== $this->request->costUnit->id) {
            $changes .= 'Kostenstelle geändert von ' . $this->request->invoice->costUnit()->first()->name . ' auf ' . $this->request->costUnit->name . '.<br />';
            $this->request->invoice->cost_unit_id = $this->request->costUnit->id;
        }


        $this->request->invoice->comment = $this->request->comment;
        $this->request->invoice->changes = $changes;

        $this->request->invoice->save();

        $request = new ChangeStatusRequest($this->request->invoice, InvoiceStatus::INVOICE_STATUS_APPROVED);
        $changeStatusCommand = new ChangeStatusCommand($request);
        $changeStatusCommand->execute();

        return $response;
    }
}
