<?php

namespace App\Domains\Admin\Controllers;

use App\Models\User;
use App\Scopes\CommonController;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class UserUpdateController extends CommonController
{
    public function __invoke(int $id, Request $request): JsonResponse
    {
        $user = User::findOrFail($id);
        $isOwnUser = auth()->id() === $user->id;
        $isLvTenant = $this->tenant->slug === 'lv';

        $allowedFields = [
            'firstname', 'lastname', 'nickname', 'email', 'phone', 'birthday',
            'membership_id', 'address_1', 'address_2', 'postcode', 'city',
            'eating_habits', 'swimming_permission', 'first_aid_permission',
            'bank_account_owner', 'bank_account_iban',
            'medications', 'allergies', 'intolerances',
            'user_role_local_group',
        ];

        if ($isLvTenant) {
            $allowedFields[] = 'local_group';
            if (!$isOwnUser) {
                $allowedFields[] = 'user_role_main';
            }
        }

        $data = $request->only($allowedFields);
        $user->update($data);

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