<?php

namespace App\Domains\Invoice\Controllers;

use App\Domains\Invoice\Actions\ChangeStatus\ChangeStatusCommand;
use App\Domains\Invoice\Actions\ChangeStatus\ChangeStatusRequest;
use App\Scopes\CommonController;
use Illuminate\Http\JsonResponse;

class ChangeStateController extends CommonController
{
    public function __invoke(int $invoiceId, string $newState) : JsonResponse {
        $invoice = $this->invoices->getAsTreasurer($invoiceId);
        if ($invoice === null) {
            return response()->json([]);
        }

        $comment = request()->get('reason') ?? null;
        $changeStatusRequest = new ChangeStatusRequest($invoice, $newState, $comment);
        $changeStatusCommand = new ChangeStatusCommand($changeStatusRequest);
        if ($changeStatusCommand->execute()->success) {
            return response()->json(['status' => 'success']);
        }

        return response()->json([]);
    }
}
