<?php

namespace App\Domains\CostUnit\Controllers;

use App\Domains\CostUnit\Actions\ChangeCostUnitState\ChangeCostUnitStateCommand;
use App\Domains\CostUnit\Actions\ChangeCostUnitState\ChangeCostUnitStateRequest;
use App\Scopes\CommonController;
use Illuminate\Http\JsonResponse;

class ChangeStateController extends CommonController {
    public function close(int $costUnitId) : JsonResponse {
        $costUnit = $this->costUnits->getById($costUnitId);

        $changeStatRequest = new ChangeCostUnitStateRequest($costUnit, false, false);
        return $this->changeCostUnitState($changeStatRequest, 'Der CostUnit wurde geschlossen.');
    }

    public function open(int $costUnitId) : JsonResponse {
        $costUnit = $this->costUnits->getById($costUnitId);

        $changeStatRequest = new ChangeCostUnitStateRequest($costUnit, true, false);
        return $this->changeCostUnitState($changeStatRequest, 'Der CostUnit wurde geöffnet.');
    }

    public function archive(int $costUnitId) : JsonResponse {
        $costUnit = $this->costUnits->getById($costUnitId);

        $changeStatRequest = new ChangeCostUnitStateRequest($costUnit, false, true);
        return $this->changeCostUnitState($changeStatRequest, 'Der CostUnit wurde archiviert.');
    }

    private function changeCostUnitState(ChangeCostUnitStateRequest $request, string $responseMessage) : JsonResponse {
        $changeStatCommand = new ChangeCostUnitStateCommand($request);

        if ($changeStatCommand->execute()) {
            return response()->json([
                'status' => 'success',
                'message' => $responseMessage
            ]);
        };

        return response()->json([
            'status' => 'error',
            'message' => 'Ein Fehler ist aufgetreten.'
        ]);
    }
}
