<?php

namespace App\Domains\Invoice\Actions\UploadInvoice;

use App\Domains\Invoice\Actions\CreateInvoiceReceipt\CreateInvoiceReceiptCommand;
use App\Domains\Invoice\Actions\CreateInvoiceReceipt\CreateInvoiceReceiptRequest;
use App\Providers\WebDavProvider;
use Illuminate\Support\Facades\Storage;

class UploadInvoiceCommand {
    private UploadInvoiceRequest $request;
    public function __construct(UploadInvoiceRequest $request) {
        $this->request = $request;
    }

    public function execute() : UploadInvoiceResponse {
        $uploadResponse = new UploadInvoiceResponse();

        $uploadDir = sprintf(
            '%1$s%2$s/%3$s',
            WebDavProvider::INVOICE_PREFIX,
            app('tenant')->url,
            $this->request->invoice->costUnit()->first()->name
        );

        $webDavProvider = new WebDavProvider($uploadDir);

        $createInvoiceReceiptRequest = new CreateInvoiceReceiptRequest($this->request->invoice);
        $createInvoiceReceiptCommand = new CreateInvoiceReceiptCommand($createInvoiceReceiptRequest);
        $response = $createInvoiceReceiptCommand->execute();
        if ('' === $response->fileName) {
            app('taskLogger')->error('PDF oder ZIP zur Abrechnung konnte nicht erstellt werden.');
            return $uploadResponse;
        }

        if ($webDavProvider->uploadFile($response->fileName)) {
            $this->request->invoice->upload_required = false;
            $this->request->invoice->save();
            $uploadResponse->success = true;
        } else {
            app('taskLogger')->error('PDF oder ZIP zur Abrechnung konnte nicht hochgeladen werden.');
        }

        if (Storage::exists($response->fileName)) {
            Storage::delete($response->fileName);
        }

        return $uploadResponse;
    }
}
