<?php

namespace App\Domains\Budget\Controllers;

use App\Domains\Budget\Actions\CreateEstimate\CreateEstimateAction;
use App\Domains\Budget\Actions\CreateEstimate\CreateEstimateRequest;
use App\Domains\CostUnit\Actions\CreateCostUnit\CreateCostUnitRequest;
use App\Scopes\CommonController;
use App\ValueObjects\Amount;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class SaveController extends CommonController
{
    public function __invoke(int $costUnitId, Request $request) : JsonResponse {
        $costUnit = $this->costUnits->getById($costUnitId);

        if ($costUnit === null) {
            return response()->json([
                'status' => 'error',
                'message' => 'Cost unit not found'
            ], 404);
        }

        $createCostUniResponse =
            new CreateEstimateAction(request: new CreateEstimateRequest(
            description: $request->input('description'),
            amount: Amount::fromString($request->input('amount')),
            amountType: $request->input('amount_type'),
            estimateType: $request->input('estimateType'),
            costUnit: $costUnit,
            estimateId: $request->input('estimateId'),
        ))->execute();

        if ($createCostUniResponse->success) {
            return response()->json([
                'status' => 'success',
                'message' => 'Der Eintrag wurde erfolgreich angelegt.'
            ]);
        } else {
            return response()->json([
                'status' => 'error',
                'message' => 'Beim Anlegen des Eintrags ist ein Fehler aufgetreten.'
            ]);
        }
    }
}
