<?php

namespace App\Domains\UserManagement\Controllers;

use App\Domains\UserManagement\Actions\UserChangePassword\UserChangePasswordCommand;
use App\Domains\UserManagement\Actions\UserChangePassword\UserChangePasswordRequest;
use App\Scopes\CommonController;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class StoreProfileController extends CommonController
{
    public function __invoke(Request $request): JsonResponse
    {
        if (!$this->checkAuth()) {
            return response()->json(['success' => false, 'message' => 'Unauthorized'], 401);
        }

        $password = $request->input('password');
        $passwordConfirmation = $request->input('password_confirmation');

        if (empty($password)) {
            return response()->json(['success' => false, 'message' => 'Bitte ein Passwort eingeben.'], 422);
        }

        if ($password !== $passwordConfirmation) {
            return response()->json(['success' => false, 'message' => 'Die Passwörter stimmen nicht überein.'], 422);
        }

        $actionRequest = new UserChangePasswordRequest(auth()->user(), $password);
        $command = new UserChangePasswordCommand($actionRequest);
        $command->execute();

        auth()->logout();
        return response()->json(['success' => true, 'message' => 'Dein Passwort wurde erfolgreich geändert.']);
    }
}
