<?php

namespace App\Domains\CostUnit\Controllers;

use App\Domains\CostUnit\Actions\ChangeCostUnitDetails\ChangeCostUnitDetailsCommand;
use App\Domains\CostUnit\Actions\ChangeCostUnitDetails\ChangeCostUnitDetailsRequest;
use App\Resources\CostUnitResource;
use App\Scopes\CommonController;
use App\ValueObjects\Amount;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class EditController extends CommonController{
    function __invoke(int $costUnitId) : JsonResponse {
        $costUnit = $this->costUnits->getById($costUnitId);
        if (null === $costUnit) {
            return response()->json([
                'status' => 'error',
                'message' => 'Die Kotenstelle konnte nicht geladen werden.'
            ]);
        }

        return response()->json([
            'status' => 'success',
            'costUnit' => new CostUnitResource($costUnit)->toArray(request())
        ]);
    }

    public function update(Request $request, int $costUnitId) : JsonResponse {
        $costUnit = $this->costUnits->getById($costUnitId);
        if (null === $costUnit) {
            return response()->json([
                'status' => 'error',
                'message' => 'Die Kotenstelle konnte nicht geladen werden.'
            ]);
        }

        $saveParams = $request->get('formData');
        $distanceAllowance = Amount::fromString($saveParams['distanceAllowance']);
        $billingDeadline = isset($saveParams['billingDeadline']) ? \DateTime::createFromFormat('Y-m-d', $saveParams['billingDeadline']) : null;

        $request = new ChangeCostUnitDetailsRequest($costUnit, $distanceAllowance, $saveParams['mailOnNew'], $billingDeadline);
        $command = new ChangeCostUnitDetailsCommand($request);
        $result = $command->execute();

        if (!$result->success) {
            return response()->json([
                'status' => 'error',
                'message' => 'Bei der Verarbeitung ist ein Fehler aufgetreten.'
            ]);
        }

        return response()->json([
            'status' => 'success',
            'message' => 'Die Kostenstellendetails wurden erfolgreich gespeichert.',
        ]);
    }
}
